Friday, April 29, 2011

Getting the class loader of a class

Bootstrap class loader is pretty special, in that it is implemented in native code. All other class loaders are written in Java (apart from some native methods) and extend the java.lang.ClassLoader class. We could get the class loader which was used to load any particular class with class.getClassLoader() method:

public class ShowClassLoaders {

    public static void main(String[] args) {
        System.out.println("class loader for Integer: "
            + Integer.class.getClassLoader());
        System.out.println("class loader for BlowfishCipher: "
            + com.sun.crypto.provider
        System.out.println("class loader for this class: "
            + ShowClassLoaders.class.getClassLoader());

When we run this program, we will see the following output:
class loader for Integer: null
class loader for BlowfishCipher: sun.misc.Launcher$ExtClassLoader@9cab16
class loader for this class: sun.misc.Launcher$AppClassLoader@d9f9c3

java.lang.Integer was loaded using the bootstrap class loader. In most implementations getClassLoader() method returns null for the bootstrap class loader. com.sun.crypto.provider.BlowfishCipher class is stored inside the <JAVA_HOME>/lib/ext/sunjce_provider.jar so it was loaded with the extensions class loader. Classes implemented by us, like the class with the main method, was loaded by system class loader.

No comments:

Post a Comment