4

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

GionJh
  • 2,742
  • 2
  • 29
  • 68

2 Answers2

4

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.

ruakh
  • 175,680
  • 26
  • 273
  • 307
2

I think what classLoader.loadClass("com.stackoverflow.MyClass") does is tell compiler to explicitly load specified class for current classLoader. In normal scenario where class is already in classpath of executing program your assumption is correct that it is already loaded by default.

However there may be situations where classes may be required to be read from other sources like - network or binary stream. In such cases default load behavior may not read those classes and loadClass() will direct compiler to explicitly load them.

For more details you can refer ClassLoader javadoc

hitz
  • 1,100
  • 8
  • 12