Monday 21 January 2013

Accessing the ClassLoader of a Class


If you want to access the ClassLoader object of a given class object, you can use the following logic:
   Class cls = obj.getClass();
   ClassLoader loader = cls.getClassLoader();
If you want to access the ClassLoader object of a given class name, you can use the following logic:
   Class cls = Class.forName(className);
   ClassLoader loader = cls.getClassLoader();
Here is tutorial example program on how to example JVM built-in ClassLoaders and access the Classloader of a given class:
/**
 * ClassloaderTest.java
 * Rishi Sharma
 */
class ClassloaderTest {
   public static void main(String[] a) {
      java.io.PrintStream out = System.out;
      Object o = null;
      Class c = null;
      ClassLoader l = null;

      l = ClassLoader.getSystemClassLoader();
      out.println("");
      out.println("Built-in ClassLoaders");
      out.println("System ClassLoader: "+l.getClass().getName());
      l = l.getParent();
      out.println("Extensions ClassLoader: "+l.getClass().getName());
      l = l.getParent();
      out.println("Bootstrap ClassLoader: "+l);

      o = new java.lang.String();
      c = o.getClass();
      l = c.getClassLoader();
      out.println("");
      out.println("ClassLoader for java.lang.String: "+l);

      o = new ClassloaderTest();
      c = o.getClass();
      l = c.getClassLoader();
      out.println("");
      out.println("ClassLoader for ClassLoaderTest: "
         +l.getClass().getName());
   }
}
When executed on Linux system with JDK 1.7.0, I got this result:

Built-in ClassLoaders

System ClassLoader: sun.misc.Launcher$AppClassLoader

Extensions ClassLoader: sun.misc.Launcher$ExtClassLoader
Bootstrap ClassLoader: null
ClassLoader for java.lang.String: null
ClassLoader for ClassLoaderTest: sun.misc.Launcher$AppClassLoader

The test result confirms that:
  • The System Classloader is implemented by the sun.misc.Launcher$ExtClassLoader class.
  • The Extensions Classloader is implemented by the sun.misc.Launcher$AppClassLoader class.
  • The Bootstrap Classload is represented as null.
  • java.lang.String is a system class, stored in <JAVA_HOME>/lib/rt.jar, and loaded by the Bootstrap ClassLoader.
  • sun.security.pkcs11.P11Util is an extension class, stored in <JAVA_HOME>/lib/ext/sunpkcs11.jar, and loaded by the Extensions ClassLoader.
  • ClassLoaderTest is my own class, stored in ./ClassloaderTest.class, and loaded by the System ClassLoader.


And this also tell me that even after 2 years of owning Java , Oracle still have not got sun.misc fixed. 


No comments:

Post a Comment