Introduction

Class loading is complex operation in Java. Whenever you create an object in program, there are a lot of things happening in the background. These include loading the class and calling the constructor. But other than these, there are a few other operations being performed by JVM. Here I shall discuss the class loading mechanism in detail with the help of an example. I am assuming that you understand the concept of class loaders in Java.

Class Loading in Action

Whenever a class is encountered for the first time in a program, JVM loads the class and all its super types. These super types could be interfaces or classes. The classes referenced in the body of this class are also loaded. Moreover, the linking of associated classes is also done at the run time. Thus Java puts more emphasis on loading of classes at run time. We can verify the above statements by writing a sample program and running it. While running the program, if you provide the arguments as -verbose:class then all classes being loaded and corresponding jar are shown on the console.

class Test1{
	public void test1() {
		System.out.println("test1");
	}
}

	
public class Test2{
	
	public static void main(String[] args) {
		Test1 t1 = new Test1();
		t2.test1();
	}
}

output:
[Opened C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.Object from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.io.Serializable from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.Comparable from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.CharSequence from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.String from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.reflect.GenericDeclaration from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.reflect.Type from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
……………………………..
……………………………..
……………………………..
[Loaded java.security.AllPermission from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.security.UnresolvedPermission from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.security.BasicPermissionCollection from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded com.example.Test2 from file:/C:/Users/sandbhan/workspace/Test/WEB-INF/classes/]
[Loaded java.lang.Void from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded com.example.Test1 from file:/C:/Users/sandbhan/workspace/Test/WEB-INF/classes/]
test1
[Loaded java.lang.Shutdown from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.Shutdown$Lock from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]

Explanation of program

The above is selected output with middle lines omitted. we can notice a few things here:

a) Most of the classes are loaded from rt.jar as it contains the all JDK core classes.
b) These JDK classes are required to run any Java program. Even if we add a blank main method in Test2.java, these JDK classes will be loaded.
c) The user classes Test2 and Test1 are loaded in the sequence of their appearance.
d) All this class loading stuff is done by the class loaders.
e) For each of the class loaded by JVM into memory, there is a corresponding object of Class created.
f) If we load a class by using Class.forName(String), then also the above points hold true.
g) There are various checks performed by the JVM at run time. These include verifying byte code, compatibility and linking checks.

Class Loading Steps

When a classes is loaded into memory, the various blocks of code are executed in some particular sequence as described below:

a) The static block of code is executed immediately after loading a class irrespective of purpose of loading the class.
In case of multiple static code blocks, they are executed in the order of appearance.
b) The constructor is invoked if a new instance of the class is created.
In case of inheritance, the super class’s constructor is invoked after invoking the subclass’s constructor.
c) The code in various methods is executed in the order in which they are invoked.

The following code shows how the order in which various blocks are executed.

	public class Test1{
		static {
			System.out.println("Test1 - Static");
		}
		Test1() {
			System.out.println("Test1 - Constructor");
		}
	}
	
		public class Test2 extends Test1{
			static {
				System.out.println("Test2 - Static");
			}
			Test2() {
				System.out.println("Test2 - Constructor");
			}
			public void test() {
				System.out.println("Test2 - test");
			}
			public static void main(String[] args) {
				System.out.println("main starting");
				Test1 t1 = new Test1();
				Test2 t2 = new Test2();
				t2.test();
			}
	}

output:
Output:
[Loaded java.lang.Object from shared objects file]
………
[Loaded java.security.Principal from shared objects file]
[Loaded Test1 from file:/C:/Sandeep/Projects/Workspace/test/bin/]
[Loaded Test2 from file:/C:/Sandeep/Projects/Workspace/test/bin/]
Test1 – Static
Test2 – Static
main starting
Test1 – Constructor
Test1 – Constructor
Test2 – Constructor
Test2 – test

In the above output we can see that the class Test1 is loaded before Test2 because super class is loaded and is needed for loading the sub class. Once both the classes are loaded, the static block of class Test1 is invoked because Test1 class was loaded first and then the static code block of class Test2 is invoked. Also we can see that the constructor for class Test1 is invoked twice, once when the object t1 is created and other when the object t2 is created.

Understanding Class Loaders

All the steps shown above for loading the classes into JVM memory are performed by a special program named as Class loader. There are three types of class loaders in Java:

BootStrap Class Loader

When you write any Java program, there are a set of JDK classes which are used in the program. These range from the Object Class to Date Class. All these classes need to be loaded into the memory before the program can use their attributes and methods. For this reason, there is a dedicated class loader which is assigned the task to load the classes from the lib folder of JRE.

The BootStrap class loader is part of the Java installation that you do on your computer and is written in native code as it has to perform memory management tasks.

Extensions Class Loader

The purpose of Extensions class loader is to load the classes and jar files present in the ext folder. The exact path of ext folder in JRE is JRE_HOME/lib/ext. If you go and see the contents of this ext directory, you shall see jar files with the name dnsns.jar, localedata.jar and sunmscapi.jar etc. These jars contain i18 and security related implementation classes from different vendors.

Moreover the java.ext.dirs system property can also be used to specify the location where the extension jar files are located.

System Class Loader

There are some third party libraries which we commonly used in our code. For e.g. Apache Commons, SSHFactory, Log4J and JSON etc. These JAR files are added to the classpath of our project in Eclipse so that JVM can locate these jar files when required. It is the job of System class loader to load the classes found in the libraries mentioned in the CLASSPATH environment variable.

User defined Class Loader

There is a class shipped with JDK named java.lang.ClassLoader. We can extend this class to write our own classloader and add custom functionality with regard to loading of classes into memory. When inheriting for ClassLoader, you can override methods and write your own implementation for how the classes are going to be loaded.

I am sure you must have used Class.forName for loading classes or JDBC drivers. There is an overloaded version of Class.forName where we can specify the classloader instanced to be used for loading the class. The exact signature of this method looks like:

Class.forName(name, initialize, loader)(className)

Class Loading Rules : This discussion on class loaders shall not be complete without letting you know some important points on class loaders:

  • Apart from Boot Strap class loader, all other class loaders have a parent class loaders.
  • When a class is requested to be loaded, each class loaders see if its parent can load the class. If the parent class loaders fail to load the class, then only the leaf node class loader loads the class.
  • If written poorly, custom class loaders can have significant adverse performance affect on your application.

Custom class loader example code:

The following code shows how we can write our custom class loader. The code has been taken from JavaLobby.

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
public class CustomClassLoader extends ClassLoader {
    public CustomClassLoader(){
        super(CustomClassLoader.class.getClassLoader());
    }
  
    public Class loadClass(String className) throws ClassNotFoundException {
         return findClass(className);
    }
 
    public Class findClass(String className){
        byte classByte[];
        Class result=null;
        result = (Class)classes.get(className);
        if(result != null){
            return result;
        }
        
        try{
            return findSystemClass(className);
        }catch(Exception e){
        }
        try{
           String classPath =    ((String)ClassLoader.getSystemResource(className.replace('.',File.separatorChar)+".class").getFile()).substring(1);
           classByte = loadClassData(classPath);
            result = defineClass(className,classByte,0,classByte.length,null);
            classes.put(className,result);
            return result;
        }catch(Exception e){
            return null;
        } 
    }
 
    private byte[] loadClassData(String className) throws IOException{
 
        File f ;
        f = new File(className);
        int size = (int)f.length();
        byte buff[] = new byte[size];
        FileInputStream fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        dis.readFully(buff);
        dis.close();
        return buff;
    }
 
    private Hashtable classes = new Hashtable();
}</i>
 
 
Here is how to use the CustomClassLoader. 
 
<i>public class CustomClassLoaderTest {
 
     public static void main(String [] args) throws Exception{
        CustomClassLoader test = new CustomClassLoader();
        test.loadClass(com.test.HelloWorld);
     }
}

References

1. Class loading mechanism
2. Classloaders in Java – Wikipedia
3. Java extensions class loader

Class Loading Mechanism in Java With Example admin Core Java
Introduction Class loading is complex operation in Java. Whenever you create an object in program, there are a lot of things happening in the background. These include loading the class and calling the constructor. But other than these, there are a few other operations being performed by JVM. Here I...
<h2>Introduction</h2> Class loading is complex operation in Java. Whenever you create an object in program, there are a lot of things happening in the background. These include loading the class and calling the constructor. But other than these, there are a few other operations being performed by JVM. Here I shall discuss the class loading mechanism in detail with the help of an example. I am assuming that you understand the concept of class loaders in Java. <div id="toc"> 1. <a href="#class loading">Class Loading in Action</a> 2. <a href="#detail">Explanation of program</a> 3. <a href="#loading steps">Class Loading Steps</a> 4. <a href="#class loader">Understanding Class Loaders</a> 5. <a href="#references">References</a> </div> <a name="class loading"></a> <h2>Class Loading in Action</h2> Whenever a class is encountered for the first time in a program, <a href="http://www.javaexperience.com/java-difference-between-jvm-jre-jdk-jit/">JVM</a> loads the class and all its super types. These super types could be interfaces or classes. The classes referenced in the body of this class are also loaded. Moreover, the linking of associated classes is also done at the run time. Thus Java puts more emphasis on loading of classes at run time. We can verify the above statements by writing a sample program and running it. While running the program, if you provide the arguments as -verbose:class then all classes being loaded and corresponding jar are shown on the console. 1 <blockquote> output: [Opened C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar] [Loaded java.lang.Object from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar] [Loaded java.io.Serializable from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar] [Loaded java.lang.Comparable from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar] [Loaded java.lang.CharSequence from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar] [Loaded java.lang.String from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar] [Loaded java.lang.reflect.GenericDeclaration from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar] [Loaded java.lang.reflect.Type from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar] ................................... ................................... ................................... [Loaded java.security.AllPermission from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar] [Loaded java.security.UnresolvedPermission from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar] [Loaded java.security.BasicPermissionCollection from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar] [Loaded com.example.Test2 from file:/C:/Users/sandbhan/workspace/Test/WEB-INF/classes/] [Loaded java.lang.Void from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar] [Loaded com.example.Test1 from file:/C:/Users/sandbhan/workspace/Test/WEB-INF/classes/] test1 [Loaded java.lang.Shutdown from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar] [Loaded java.lang.Shutdown$Lock from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar] </blockquote> <a name="detail"></a> <h2>Explanation of program</h2> The above is selected output with middle lines omitted. we can notice a few things here: <strong>a)</strong> Most of the classes are loaded from <a href="http://www.javaexperience.com/important-jar-files-in-jre/">rt.jar</a> as it contains the all JDK core classes. <strong>b)</strong> These JDK classes are required to run any Java program. Even if we add a blank <a href="http://www.javaexperience.com/main-method-in-java/">main method</a> in Test2.java, these JDK classes will be loaded. <strong>c)</strong> The user classes Test2 and Test1 are loaded in the sequence of their appearance. <strong>d)</strong> All this class loading stuff is done by the class loaders. <strong>e)</strong> For each of the class loaded by JVM into memory, there is a corresponding object of Class created. <strong>f)</strong> If we load a class by using Class.forName(String), then also the above points hold true. <strong>g)</strong> There are various checks performed by the JVM at run time. These include verifying byte code, compatibility and linking checks. <a name="loading steps"></a> <h2>Class Loading Steps</h2> When a classes is loaded into memory, the various blocks of code are executed in some particular sequence as described below: <strong>a)</strong> The static block of code is executed immediately after loading a class irrespective of purpose of loading the class. In case of multiple static code blocks, they are executed in the order of appearance. <strong>b)</strong> The constructor is invoked if a new instance of the class is created. In case of inheritance, the <a href="http://www.javaexperience.com/this-and-super-in-java/">super class’s constructor</a> is invoked after invoking the subclass’s constructor. <strong>c)</strong> The code in various methods is executed in the order in which they are invoked. The following code shows how the order in which various blocks are executed. 1 <blockquote> output: Output: [Loaded java.lang.Object from shared objects file] ......... [Loaded java.security.Principal from shared objects file] [Loaded Test1 from file:/C:/Sandeep/Projects/Workspace/test/bin/] [Loaded Test2 from file:/C:/Sandeep/Projects/Workspace/test/bin/] Test1 - Static Test2 - Static main starting Test1 - Constructor Test1 - Constructor Test2 - Constructor Test2 - test </blockquote> In the above output we can see that the class Test1 is loaded before Test2 because <a href="http://www.javaexperience.com/this-and-super-in-java/" title="this and super keywords">super</a> class is loaded and is needed for loading the sub class. Once both the classes are loaded, the static block of class Test1 is invoked because Test1 class was loaded first and then the static code block of class Test2 is invoked. Also we can see that the constructor for class Test1 is invoked twice, once when the object t1 is created and other when the object t2 is created. <a name="class loader"></a> <h2>Understanding Class Loaders</h2> All the steps shown above for loading the classes into <a href="http://www.javaexperience.com/jvm-memory-areas-and-categories/" title="JVM Memory areas">JVM memory</a> are performed by a special program named as Class loader. There are three types of class loaders in Java: <h3>BootStrap Class Loader</h3> When you write any Java program, there are a set of JDK classes which are used in the program. These range from the Object Class to Date Class. All these classes need to be loaded into the memory before the program can use their attributes and methods. For this reason, there is a dedicated class loader which is assigned the task to load the classes from the lib folder of JRE. The BootStrap class loader is part of the Java installation that you do on your computer and is written in native code as it has to perform memory management tasks. <h3>Extensions Class Loader</h3> The purpose of Extensions class loader is to load the classes and jar files present in the ext folder. The exact path of ext folder in JRE is JRE_HOME/lib/ext. If you go and see the contents of this ext directory, you shall see jar files with the name dnsns.jar, localedata.jar and sunmscapi.jar etc. These jars contain i18 and security related implementation classes from different vendors. Moreover the java.ext.dirs system property can also be used to specify the location where the extension jar files are located. <h3>System Class Loader</h3> There are some third party libraries which we commonly used in our code. For e.g. Apache Commons, SSHFactory, Log4J and JSON etc. These JAR files are added to the classpath of our project in Eclipse so that JVM can locate these jar files when required. It is the job of System class loader to load the classes found in the libraries mentioned in the <a href="http://www.javaexperience.com/setting-path-classpath-and-java_home-enviornment-variables/" title="Setting PATH, CLASSPATH and JAVA_HOME environment variables">CLASSPATH environment variable</a>. <h3>User defined Class Loader</h3> There is a class shipped with JDK named java.lang.ClassLoader. We can extend this class to write our own classloader and add custom functionality with regard to loading of classes into memory. When inheriting for ClassLoader, you can override methods and write your own implementation for how the classes are going to be loaded. I am sure you must have used Class.forName for loading classes or <a href="http://www.javaexperience.com/java-database-connectivity/" title="Java Database Connectivity">JDBC drivers</a>. There is an overloaded version of Class.forName where we can specify the classloader instanced to be used for loading the class. The exact signature of this method looks like: <blockquote>Class.forName(name, initialize, loader)(className)</blockquote> <strong>Class Loading Rules : </strong> This discussion on class loaders shall not be complete without letting you know some important points on class loaders: <ul> <li>Apart from Boot Strap class loader, all other class loaders have a parent class loaders.</li> <li>When a class is requested to be loaded, each class loaders see if its parent can load the class. If the parent class loaders fail to load the class, then only the leaf node class loader loads the class.</li> <li>If written poorly, custom class loaders can have significant adverse performance affect on your application.</li> </ul> <strong>Custom class loader example code:</strong> The following code shows how we can write our custom class loader. The code has been taken from JavaLobby. 1 <a name="references"></a> <h2>References</h2> 1. <a href="http://www.onjava.com/pub/a/onjava/2005/01/26/classloading.html" target="_blank">Class loading mechanism</a> 2. <a href="http://en.wikipedia.org/wiki/Java_Classloader" target="_blank">Classloaders in Java - Wikipedia</a> 3. <a href="http://docs.oracle.com/javase/tutorial/ext/basics/load.html" target="_blank">Java extensions class loader</a>
The following two tabs change content below.
I run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database. Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post. Thanks for the support.

Latest posts by admin (see all)