Monday, October 29, 2012

Static class loader

I was just wandering, how to identified class loader for static block.

We can find the class loader for a class by using following :
        this.getClass().getClassLoader()

So here is small piece of code to find the classloader for static block.


class Loader {
   // static final String theName = "The Loader";
   static String s = "";
    static {
         try {
Class c = Class.forName(Loader.class.getName());
s = c.getClassLoader().toString();
} catch (ClassNotFoundException e) {
}
        System.out.println("Loader.static  : " + s);
        System.out.println("Loader.static Loader : " + ClassLoader.getSystemClassLoader() ) ;
    }


    Loader() {
        System.out.println("Loader.Loader()");
    }
} // End of Loader

public class ClasLoaderTest {
    static {
        System.out.println( "Test.static");
    }
    ClasLoaderTest() {
Loader l = new Loader();
        System.out.println( "Test.Test()");
    }
    public static void main( String [] args ) {
        System.out.println( "Test.main");
        ClasLoaderTest t = new ClasLoaderTest();
t.myMeth();
        System.exit(0);
    }

    public void myMeth() {
        String s = this.getClass().getClassLoader().toString();
        System.out.println( "Class Loader " + s);

}

}// End of ClasLoaderTest


Above sample code is taken from http://www.engfers.com/code/static-initializer-block/ .
Please let me know if there is any copy right violation or any other infringements.

Output is following:


Test.static
Test.main
Loader.static  : sun.misc.Launcher$AppClassLoader@fabe9
Loader.static Loader : sun.misc.Launcher$AppClassLoader@fabe9
Loader.Loader()
Test.Test()
Class Loader sun.misc.Launcher$AppClassLoader@fabe9