ClassLoader in Java works on three principle: delegation, visibility andUniqueness. Delegation principle forward request of class loading to
Parent class loader and only loads
the class if parent is not able to locate or load class.Visibility principles allows Child ClassLoader to see all the classes loaded byParent ClassLoader but parent ClassLoader can not see classes loaded by childClassLoader. Uniqueness principle allows to load
a class exactly once which isbasically achieved by delegation and ensures that Child ClassLoader doesn'treload the class loaded by Parent ClassLoader. Correct understanding ofClassLoader is must to resolve issues like NoClassDefFoundErrorin Java and java.lang.ClassNotFoundExceptionwhich are related to class loading. ClassLoader is also an important topic inadvance Java Interview where good
knowledge of working of class loader and Howclasspath works in Java is expectedfrom
Java programmer. I have always see questions like
Can one class beloaded by two different ClassLoader in Java on various JavaInterviews. In this ClassLoadertutorial we will see What is ClassLoaderin Java, How ClassLoader works in Java and some specifics about ClassLoader inJava.
Whatis ClassLoader in Java
ClassLoader in Java is a mechanism which is used to load classfiles in Java.
Java code is compiled into
class file by javac compilerand JVM executes
Java program by executing byte codes written in class file.ClassLoader is responsible for loading class files from file system, network orany other source. There are three default ClassLoader used in Java
BootstrapClassLoader,
Extension ClassLoader and
System orApplicationclass loader. Every ClassLoader has a predefined location from where theyloads class files.
Bootstrap ClassLoader is responsible for loading standardJDK class files from rt.jar and its parent of all ClassLoaderin Java, But Bootstrap ClassLoader doesn't have any parents if you call String.class.getClassLoader() it willreturn null. Bootstrap ClassLoader is also called
PrimordialClassLoader in Java. ExtensionClassLoader delegates class loading request to its parent Bootstrap ClassLoaderand if unsuccessful loads class form jre/lib/ext directoryor any other directory pointed by java.ext.dirs Systemproperty. Extension ClassLoader in JVM is implemented by sun.misc.Launcher$ExtClassLoader. Thirdclass loader used by JVM to load Java classes is called System
or ApplicationClassLoader and it is responsible for loading application specific Java classfiles from location specified in CLASSPATHenvironment variable, -classpath or -cp commandline option, Class-Path attribute of Manifest file insideJAR. Application ClassLoader is a child of Extension ClassLoader and itsimplemented by sun.misc.Launcher$AppClassLoader class.Also except Boot Strap class loader which is implemented in native languagemostly in C, all ClassLoader in Java isimplemented using java.lang.ClassLoader.
In short here is the location from which Bootstrap, Extension andApplication ClassLoader load Class files.
1) Bootstrap ClassLoader - JRE/lib/rt.jar
2) Extension ClassLoader - JRE/lib/ext or any directory denoted by java.ext.dirs
3) Application ClassLoader - CLASSPATH environment variable, -classpathor -cp option, Class-Path attribute of Manifest inside JARfile.
How ClassLoader works in Java
As I explained earlier ClassLoader works in three principles :delegation, visibility and uniqueness. In this section we will see these rulesin detail and understand working of ClassLoader with example:
Delegationprinciples
As discussed Whena class is loaded and initialized in Java, a class is loaded in Java whenits needed. Suppose you have an application specific class called Abc.class, firstrequest of loading this class will come to Application ClassLoader which willdelegate to its parent Extension ClassLoader which further delegates toPrimordial or Bootstrap class loader. Primordial Class loader will look forthat class in rt.jar and since that class is notthere, request comes to Extension class loader which looks on jre/lib/extdirectory and tries to locate this class there, if class is found therethan Extension classLoader will load that class and Application class loaderwill never load that class but if its not loaded by extension classLoader thanApplication class loader loads it from Classpathin Java. Remember ClassPath is used to load class files while PATHis used to locate executable like javac or java command.
VisibilityPrinciple
According to visibility principle, Child ClassLoader can see class loadedby Parent ClassLoader but vice-versa is not true. Which mean if class Abc is loadedby Application class loader than trying to load class ABC explicitly usingextension ClassLoader will throw either java.lang.ClassNotFoundException.as shown in below Example
package
test
;
import
java.util.logging.Level
;
import
java.util.logging.Logger
;
/**
* Java program to demonstrate How ClassLoader works in Java,
* in particular about visibilityprinciple of ClassLoader.
*
* @author http://javarevisited.blogspot.com
*/
public classClassLoaderTest
{
public static voidmain
(
String args
[])
{
try
{
//printingClassLoader of this class
System.
out.
println
(
"ClassLoaderTest.getClass().getClassLoader(): "
+ ClassLoaderTest.
class.
getClassLoader
())
;
//tryingto explicitly load this class again using Extension class loader
Class.
forName
(
"test.ClassLoaderTest",
true
, ClassLoaderTest.
class.
getClassLoader
().
getParent
())
;
}
catch
(
ClassNotFoundExceptionex
)
{
Logger.
getLogger
(ClassLoaderTest.
class.
getName
()).
log
(
Level.
SEVERE,
null, ex
)
;
}
}
}
Output:
ClassLoaderTest.
getClass
().
getClassLoader
() : sun.
misc.
Launcher$AppClassLoader@601bb1
16/08/
2012
2:
43:
48 AM test.
ClassLoaderTestmain
SEVERE:
null
java.
lang.
ClassNotFoundException:test.
ClassLoaderTest
at java.
net.
URLClassLoader$
1.
run
(
URLClassLoader.
java:
202
)
at java.
security.
AccessController.
doPrivileged
(Native
Method
)
at java.
net.
URLClassLoader.
findClass
(
URLClassLoader.
java:
190
)
at sun.
misc.
Launcher$ExtClassLoader.
findClass
(Launcher.
java:
229
)
at java.
lang.
ClassLoader.
loadClass
(
ClassLoader.
java:
306
)
at java.
lang.
ClassLoader.
loadClass
(
ClassLoader.
java:
247
)
at java.
lang.
Class.
forName0
(Native
Method
)
at java.
lang.
Class.
forName
(
Class.
java:
247
)
at test.
ClassLoaderTest.
main
(ClassLoaderTest.
java:
29
)
Uniqueness Principle
According to this principle a class loaded by Parent should not be loadedby Child ClassLoader again. Though its completely possible to write class loaderwhich violates Delegation and Uniqueness principles and loads class by itself,its not something which is beneficial. You should follow all classloader principle while writing your ownClassLoader.
How to load class explicitly in Java
Java provides API to explicitly load a class by Class.forName(classname) and Class.forName(classname,initialized, classloader), remember JDBC code which is used to load JDBCdrives we have seen in Javaprogram to Connect Oracle database. As showin in above example you can passname of ClassLoader which should be used to load that particular classalongwith binary name of class. Class is loaded by calling loadClass() method of java.lang.ClasSLoader classwhich calles findClass() method to locate bytecodes forcorresponding class. In this example Extension ClassLoader uses java.net.URLClassLoader whichsearch for class files and resources in JARand directories. any search path which is ended using "/" isconsidered directory. if findClass() does not found the class than itthrows java.lang.ClassNotFoundExceptionand if it finds it calls defineClass() to convert bytecodes into a.class instance which is returned to the caller.
Whereto use ClassLoader in Java
ClassLoader in Java is a powerful concept and used at many places. One ofthe
popular example of ClassLoader isAppletClassLoader which is used to load class by Applet, since Applets are mostlyloaded from internet rather than local file system, By using separateClassLoader you can also loads same class from mutiple sources and they will betreated as different class in JVM.J2EE uses multiple class loaders to load class from different location likeclasses from WAR file will be loaded by WebApp ClassLoader while classesbundeled in EJB-JAR is loaded by another class loader. Some webserver alsosupports hot deploy functionality which is implemented using ClassLoader. Youcan also use ClassLoader to load classes from database or any other persistentsotre.
That's all about
What is ClassLoader in Java and
HowClassLoader works in Java. We have seen delegation, visibility anduniqueness principles which is quite important to debug or troubleshoot anyClassLoader related issues in Java. In summary knowledge of How ClassLoaderworks in Java is must for any Java developer or architect to design Javaapplication and packaging.
Read more: http://javarevisited.blogspot.com/2012/12/how-classloader-works-in-java.html
http://www.ibm.com/developerworks/cn/java/j-lo-classloader/index.html
http://wenku.baidu.com/view/04671bd480eb6294dd886c79.html
http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html