What is Static and Dynamic class loading ?

The static class loading is done through the new operator.

class MyClass {     
public static void main(String args[]) {
Car c = new Car();
}
}
Dynamic class 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. 

//static method which returns a Class
Class.forName (String className);
The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time. 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.

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

public static void main(String args[]){
String myCarClassPath = "com.tuturself.Car" ;
Class vehicleClass = Class.forName(myCarClassPath) ;
Car car = (Car) vehicleClass.newInstance();
car.setMake("Maruti");
}
Context class loader: Context class loaders are attached to threads, not classes.

ClassLoader context = Thread.currentThread().getContextClassLoader();

core java 12

FOLLOW US ON LinkedIn



Explore Tutu'rself