Java: Difference between Class.forName and ClassLoader.loadClass

IAmYourFaja picture IAmYourFaja · Dec 1, 2011 · Viewed 31.2k times · Source

What is the difference between Class.forName and ClassLoader.loadClass in the following codes:

Class theClass = Class.forName("SomeImpl");
SomeImpl impl = (SomeImpl)theClass.newInstance();

and

Class theClass = ClassLoader.loadClass("SomeImpl");
SomeImpl impl = (SomeImpl)theClass.newInstance();

Are they synonymous? Is one preferable to the other in certain circumstances? What are the do's and dont's when using these two methods?

Answer

Shaun picture Shaun · Dec 1, 2011

Class.forName() will always use the ClassLoader of the caller, whereas ClassLoader.loadClass() can specify a different ClassLoader. I believe that Class.forName initializes the loaded class as well, whereas the ClassLoader.loadClass() approach doesn't do that right away (it's not initialized until it's used for the first time).

Just found this article when looking to confirm my summary of the initialization behavior. It looks like this has most of the information you're looking for:

http://www.javaworld.com/javaworld/javaqa/2003-03/01-qa-0314-forname.html

This usage is pretty cool, though I've never used it before:

Class.forName(String, boolean, ClassLoader)

It allows you to specify a ClassLoader and the boolean parameter defines whether the class should be initialized when it's loaded or not.