Class.forName() doesn't instantiate an object (at least not an object of the class you are calling it for, it might instantiate a Class object). All it does is preload the class for the given name, allowing objects to be instantiated from it.
Class.forName().newInstance() would actually create an instance.
This is useful in situations when the class name to be instantiated cannot be known at compile time. [ April 07, 2005: Message edited by: Jeroen Wenting ]
First and foremost difference is that you won't ever get a compilation error while using Class.forName(String ...), But if you use new operator, then the class must exist and must compile without errors.
Second, while using Class.forName(String ...), the class must be public and must have a no-arg public constructor. This restriction is not in the case of using new operator. Here you can instantiate with arguments.
Another difference is that the class will be loaded and verified only when Class.forName is executed.
Then coding difference of method 2 calls.
Class.forName("MyClass").newInstance(); // note: reflection api comes into picture here
new MyClass(); // single direct call to constructor here
So I believe the use of "new" operator is efficient than using its counterpart.
What do you think ...
Joined: Oct 12, 2000
Class.forName() will give a runtime error in case the class you're trying to load doesn't exist on the classpath. Instantiation using new will give a compiler error if the class doesn't exist on the classpath during compilation as well as a runtime error if it doesn't exist at runtime. You can use reflection to instantiate classes without a no-argument constructor, but it's slightly more involved than just calling newInstance() on the Class. You have to call Class.forName(...).getConstructor(...).newInstance(...) while supplying the correct argument list go getConstructor() and newInstance() as an array of Class objects (or using varargs) for getConstructor() and an array (or varargs) of correctly typed objects for newInstance().
Class.forName() is one technique among many to achieve "abstraction". Abstraction means ignoring unnecessary details so the necessary details become visible. I might use Class.forName(x).newInstance() when I know what interface or base class the new object will be derived from, but I don't know the exact class of the new object.
In real life I do this all the time to get the actual class from configuration, so my application can run with one repository or another without changing any code. I don't have to know if this is a file based repository or a database repository:
If that was too advanced and made no sense, I apologize. If it sounded kind of cool, scroll on down to the UML, OO, etc. forum for many such conversations.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi