Forums Register Login
Difference between Class.forName() and Class.forName().getInstance()

I am really very much confused Difference between Class.forName() and Class.forName().getInstance()
Can anyone explain me the difference between the two.

Thank you,
What class does getInstance() belong to?
I don't see it in the Class class.
Yes, there is no method getInstance() for Class. But people usually use it to load the class dynamically.

What class is getInstance() in?
He means "newInstance()".

Class.forName() returns a Class object -- an object that represents a particular Java class. newInstance() -- a method of java.lang.Class -- will use the no-argument constructor of the represented class to create an instance of that class.
One example I can think of is the old days of JDBC. You can still see examples of this workaround in current code through the wonders of "cut and paste".

As EFH says, Class.forName() gets a reference to a Class, Class.forName().newInstance() tries to use the no-arg constructor for the Class to return a new instance. No surprises so far. Another common use for Class.forName() is to cause the Class to be loaded, since some types of Classes have side-effects from the loading process which is required for other purposes. JDBC is a large user of this process, since the Driver class is required to register itself with the DriverManager Class when it gets loaded.

In the deep dark days of Java, probably v1.1.8 but possibly up to Java 1.2, there was an issue that the default ClassLoader would not load a Class until it had an instance created. In these cases, JDBC code would fail if you used Class.forName() rather than Class.forName().newInstance().

While newInstance() would create an instance that got immediately thrown away, it was required to make Class.forName() work correctly. This work around is no longer required, but I am amused to still see it in code being written to this day.

There was a similar ClassLoader problem which was solved by attaching a non-running static thread to a Class to prevent it being unloaded by the ClassLoader, but again I haven't seen any need for this for many a year.

Thanks David O'Meara and Ernest Friedman-Hill. You have given lot of information and cleared my doubt conceptually. I specially thank David O'Meara for his detailed explanation.
We try. I'm glad we managed to help.
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards

All times above are in ranch (not your local) time.
The current ranch time is
Oct 21, 2017 13:26:35.