Explain static vs. dynamic class loading?

Static class loading

1.Classes are statically loaded with Java’s “new” operator.
class MyClass {
    public static void main(String args[]) {
        Car c = new Car();
    }
}

2. A NoClassDefFoundException is thrown if a class is referenced with Java’s “new” operator (i.e. static loading) but the run time system cannot find the referenced class.

Dynamic class loading

Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Let us look at how to load classes dynamically.

Class.forName (String className); //static method which returns a Class

The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime conditions. Once the class is dynamically loaded the following method returns an instance of the loaded class. It’s just like creating a class object with no arguments.

class.newInstance (); //A non-static method, which creates an instance of a class (i.e. creates an object).

Jeep myJeep = null ;
//myClassName should be read from a properties file or Constants interface. //stay away //from hard coding values in your program. 
String myClassName = “au.com.Jeep” ;
Class vehicleClass = Class.forName(myClassName) ;
myJeep = (Jeep) vehicleClass.newInstance();
myJeep.setFuelCapacity(50);

A ClassNotFoundException is thrown when an application tries to load in a class through its string name using the following methods but no definition for the class with the specified name could be found:

  1. 􀂃 The forName(..) method in class – Class.
  2. 􀂃 The findSystemClass(..) method in class – ClassLoader.
  3. 􀂃 The loadClass(..) method in class – ClassLoader.

What are “static initializers” or “static blocks with no function names”? When a class is loaded, all blocks that are declared static and don’t have function name (i.e. static initializers) are executed even before the constructors are executed. As the name suggests they are typically used to initialize static fields.

public class StaticInitilaizer {
    public static final int A = 5;
    public static final int B;
    //Static initializer block, which is executed only once when the class is loaded.

    static {
        if(A == 5)
            B = 10;
        else
            B = 5;
    }
    public StaticInitilaizer(){} // constructor is called only after static initializer block
}

The following code gives an Output of A=5, B=10.

public class Test {
    System.out.println(“A =” + StaticInitilaizer.A + “, B =” + StaticInitilaizer.B);
}

Leave a comment