Example & Tutorial understanding programming in easy ways.

What’s the difference between static and dynamic class loading?

 

                                        static class loading                               dynamic class loading
1 In static class loading, usuall classes are loaded with Java’s “new” operator.

2 For example,

class MyClass {

public static void main(String args[]) {

Car c = new Car();}}

3 JVM throws NoClassDefFoundException if a class is referenced with Java’s "new" operator (i.e. static loading) but the runtime system or JVM can not find the referenced class.

1 When you try to load the class programmatically (here class name is supplied by some property file or from some external source) by invoking the functions of a class loader at run time, It referred as dynamic classloading.

2 For example

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

The above static method returns the class object associated with the class name and 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.

 For example,

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

3 JVM throws ClassNotFoundException exception when an application tries to load in a class through its string name but could not find the definition for the class with the specified name.

 

 

 

Read More →