This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
I am really very much confused Difference between Class.forName() and Class.forName().getInstance() Can anyone explain me the difference between the two.
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.
/Dave
Kalyan Patti
Greenhorn
Joined: Jun 27, 2006
Posts: 22
posted
0
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.