How does a ClassLoader work in Java?

JavaObject Oriented ProgrammingProgramming

A Java Class is stored in the form of byte code in a .class file after it is compiled. The ClassLoader loads the class of the Java program into memory when it is required. The ClassLoader is hierarchical and so if there is a request to load a class, it is delegated to the parent class loader.

The types of ClassLoader in Java are given as follows

  • Bootstrap ClassLoader
  • Extensions ClassLoader
  • System ClassLoader

Example

public class ClassLoaderTest {
   public static void main(String[] args) {
      System.out.println("class loader for this class: " + ClassLoaderTest.class.getClassLoader());
      System.out.println("class loader for DNSNameService: " + sun.net.spi.nameservice.dns.DNSNameService.class.getClassLoader());
      System.out.println("class loader for HashMap: " + java.util.HashMap.class.getClassLoader());
   }
}

Output

class loader for this class: sun.misc.Launcher$AppClassLoader@73d16e93
class loader for DNSNameService: sun.misc.Launcher$ExtClassLoader@70dea4e
class loader for HashMap: null
raja
Published on 30-Aug-2019 17:24:54
Advertisements