Wednesday, May 25, 2011

Static class loading vs Dynamic class loading

There are two ways in which classes can be loaded -- explicitly or dynamic or implicitly or static-- with subtle variations between the two.
Static Class Loading
Classes are statically loaded with Java’s 'new' operator.
class MyClass 
{     
    public static void main(String args[]) 
   { 
        Car c = new Car(); 
   }
}


A NoClassDefFoundException is thrown if a class is referenced with Java’s 'new' operator (i.e. static loading) but the runtime 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.
we can load classes dynamically by...
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);

Summary
Explicit class loading occurs when a class is loaded using one of the following method calls:
  • cl.loadClass() (where cl is an instance of java.lang.ClassLoader)
  • Class.forName() (the starting class loader is the defining class loader of the current class)
When one of these methods is invoked, the class whose name is specified as an argument is loaded by the class loader. If the class is already loaded, then a reference is simply returned; otherwise, the loader goes through the delegation model to load the class.

Implicit class loading occurs when a class is loaded as result of a reference, instantiation, or inheritance (not via an explicit method call). In each of these cases, the loading is initiated under the covers and the JVM resolves the necessary references and loads the class. As with explicit class loading, if the class is already loaded, then a reference is simply returned; otherwise, the loader goes through the delegation model to load the class.

1 comment:

  1. Interesting one. Thanks for the share. Keep posting such kind of post on your blog. I bookmarked it for continuous visit.
    html5 audio player

    ReplyDelete

Chitika