What is the purpose of the Java Class loader?

Viewed 2944

My question is, when does JVM load all the classes in the project? Also, why do we need the notion of a class loader.

I'd be happy if you could give me a example of a situation where you use class loader and why you use class loader in that situation.

7 Answers

Default Class Loader will load .class file only once, even though you are using that multiple times in your program. After loading.class file, if it is modified outside then default class loader wont load updated version of class file(.class file is already available in method area). You can resolve this problem, by defining your own customized Class Loader.

Main advantage of customized class loader is you can control, class loading mechanism based on your requirement.

java.lang.ClassLoader to define own customized class loader. Every class loader in JAVA should be child class of java.lang.ClassLoader class, either directly of indirectly. Hence, this class acts as base class for all customized class loaders.

Note: While designing/developing web servers and application server, usually customized class loaders are used to customized class loading mechanism.

For example:

public class CustClassLoader extends ClassLoader{
     public Class loadClass(String cname) throws ClassNotFoundException{
     //check for updates and laod updated .class
     //file and returns corresponding Class
     }
}

class Client{
    public static void main(String [] args){
         Dog d1 = new Dog();
         CustClassLoader c1 = new CustClassLoader();
         c1.loadClass("Dog");
         //
         // 
         //
         c1.loadClass("Dog");
         //
     //
     }
}
Related