Friday, March 25, 2016

Static Class Loading vs Dynamic Class Loading

When we create a object with new operator , that class is loaded with static class loader. With static class loader class definition is loaded in compile time.
With static class loading , we can construct an object with either no arg/args constructors.

There are very less chances for runtime exception with new operator. Only rare case is when the class was present during compile time but was not available on classpath during runtime.  In that case we will get "NoClassDefFoundError"

Dynamic class Loading :
 With a name of a class, we can load a class on runtime too.

  A a = (A) Class.forName("A").newInstance();

Dynamic class loading needs the class to have a no arg constructor.Otherwise in runtime,
we will get exeption(java.lang.NoSuchMethodException)

But dynamic class loading is slower.  The JVM will locate the class, instantiate it with reflection(look up for a no arg constructor) , then typecast it.
If the mentioned class is not found , dynamic class loading will throw "ClassNotFoundException".

We can create a class instance dynamically by using Class.forName("className") or by
using loadClass of a classLoader, ex ClassLoader.getSystemClassLoader().loadClass("className");

the forName() once loads a class using the current class loader and it initializes all static members of the class.
But loadClass() does not initialize static members of the class , unless it is used first time.

ex :

class TestClass1{
static {

        System.out.println("Static Initializer Called!!"};


}
        }

Class.forName("TestClass1") --> will print  "Static Initializer Called!!";
ClassLoader.getSystemClassLoader().loadClass("TestClass1") --> will not print

No comments:

Post a Comment