Search code examples
javareflectionclassloader

Difference between Loading a class using ClassLoader and Class.forName


Below are 2 code snippets

The first one uses ClassLoader class to load a specified class

ClassLoader cls = ClassLoader.getSystemClassLoader(); Class someClass = cls.loadClass("TargetClass");

The second one uses Class.forName() to load a specified class

Class cls = Class.forName("TargetClass");

What is the difference between the above said approaches. Which one serves for which purpose?


Solution

  • Quick answer (without code samples)

    With the explicit ClassLoader cls = <a ClassLoader>; approach you have the flexibility of loading the class from a ClassLoader that is not your default ClassLoader. In your case you're using the default System ClassLoader, so it gives the similar overall result (with an instantiation of the final object difference) as the Class.forName(String name) call, but you could reference another ClassLoader instead.

    That said, you can also use Class.forName(String name, boolean initialize, ClassLoader loader) as long as you know what that ClassLoader is.

    For example, your EAR based application has its own ClassLoader with a version of an XML Parsing library wrapped inside of it. Your code normally uses those classes, but in one instance you need to grab a deserialisation class from an earlier version of the library (that the Application Server happens to be holding in its overall ClassLoader). So you could reference that Application Server ClassLoader instead.

    Unfortunately until we get project Jigsaw (JDK 8) this is used more often than we'd like :-)