Search code examples
javaclassjvmclassloaderdynamic-loading

Proper definition of java dynamic class loading


In my understanding all java classes are loaded dynamically into memory, that is when JVM sees for the first time a CLASS symbol, it loads its content into memory.

In java we are used to say we are making the JVM load a class dynamically when doing the following:

(1)

 Class aClass = classLoader.loadClass("com.stackoverflow.MyClass");

But, from what I said before, to me it seems that the JVM does always the same thing. I mean no more steps are needed to load a class using snippet (1), than are needed when loading a class when the JVM bumps for the first time into a CLASS symbol.

Am I getting something wrong ? Are they two different concepts all along ? thanks


Solution

  • Well, they're not exactly the same, but overall, you're right that classLoader.loadClass("com.stackoverflow.MyClass") gives basically the same effect as simply referring to com.stackoverflow.MyClass inside your class.

    The main power of classLoader.loadClass and Class.forName and so on is that they let you load a class that is not named by a hardcoded string. For example, the class-name may appear in a configuration file. (The Spring framework, for example, does as much of this as anyone could possibly want.)

    Secondarily, these methods also raise a more-handleable exception in the case that the class can't be loaded. For example, SLF4J provides a single API JAR-file that other libraries can compile against, but several different implementation JAR-files that the end application can deploy with (one that delegates to Log4j, one that delegates to java.util.logging.Logger, etc.). At runtime, SLF4J tries to find the deployed implementation by dynamically loading org.slf4j.impl.StaticLoggerBinder, but if it can't find one, it just prints a warning (and defaults to a no-op implementation) rather than blowing up. This approach would not work if the classes in the SLF4J API JAR-file depended statically on the org.slf4j.impl.StaticLoggerBinder class.