Search code examples
javastaticclassloader

Class Loading, static block


I have this piece of code, i am running it using -verbose:class option to see the classes that got loaded. To my surprise, it shows it loaded class A1 and A2 but the static block is not getting called.

Can someone plz explain this behavior

package P1;



import java.lang.reflect.InvocationTargetException;

public class DemoReflection {

    static {
        System.out.println("Loading Demo");
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException,
            InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        System.out.println("A2 " + A2.class.getClassLoader().getClass());
        System.out.println("Demo " + DemoReflection.class.getClassLoader().getClass());
        System.out.println("A1 " + A1.class.getClassLoader().getClass());
    }

}

class A1 {
    static {
        System.out.println("Loading A1");
    }
}

class A2 extends A1 {

    static {
        System.out.println("Loading A2");
    }

    public A2() {
        System.out.println("m2");
    }

    public void m1() {
        System.out.println("m1");
    }
}

class A3 {

    static int a3Id = 3;

    static {
        System.out.println("Loading A3");
    }

}

Output: enter image description here


Solution

  • Simple version: Static block runs only at first time you make an object or you access a static member of that class.