Search code examples
javaclassclassloader

Calling Class.forName() twice


I am currently reading Class loader and their hierarchy functionality. If I call below code -

ClassA a=  Class.forName("com.test.ClassA")

As per my understanding,now it will be initialized and loaded in memory with help of Application Class loader. I have below questions:

  1. What will happen if I call again call the above code? Will there be new instance created in memory for 'ClassA' or will it return the same loaded class reference?
  2. If yes, as per this post of javarevisited,"By using separate ClassLoader you can also loads same class from multiple sources and they will be treated as different class in JVM" What will be use of it?

Solution

    1. You will get the same class. Just test it. Load it a second time and check if a1 == a2.
    2. The most frequent usage of this feature is probably in app servers: you can deploy several web applications in a single server, and all can use the same classes. But they shouldn't share static variables. And if one uses class Foo from library 1.0, and the other one uses class Foo from library 2.0, there should be no problem. Hence the need to load the same class with different class loaders.