Monday 17 November 2014

What is static and dynamic class loading in Java?

Static Class Loading: Creating objects and instance using new keyword is known as static class loading. The retrieval of class definition and instantiation of the object is done at compile time.

Using new operator you load classes statically in java.

public static void main(String[] args)
{
 Sample m = new Sample();
}

Dynamic Class Loading: Dynamic class loading is done when the name of the class is not known at compile time. Dynamic class loading also called as reflection.This can be achieved by invoking the Class loader functions programmatically. Typically we use Class.forName(String className) to get the class first and then we will call the newInstance() method on the returned class to get the instance.

For example if you want to get a instance of Sample class using dynamic class loading, you have to ...
Sample sample = null;
Class sampleClass = Class.forName("com.sample.Sample");
sample = (Sample) sampleClass.newInstance();
sample.doSomeThing();
Here in dynamic class loading ClassNotFoundException can be thrown if given Class loader doesn’t find the given Class name (com.sample.Sample) in the classpath. Class Loader looks for a given class in following sequence:

  • The forName(..) method in the class called Class
  • The findSystemClass(..) method in the class class called ClassLoader
  • The loadClass(..) method in the class called ClassLoader