Thursday, November 1, 2012

How to create an orthodox mysterious NoClassDefFoundError

When I began my current job, I also began encountering NoClassDefFoundErrors in different places. At that time I had never seen them before, and for long I have been puzzled how they are created.

Now, I finally understood how to create it correctly. Enjoy :)

public class A {
   
    public static final A INSTANCE = new A();
   
    static {
        throwError();
    }
   
    private static void throwError() {
        throw new RuntimeException();
    }
}

public class T {
    static {
        try {
            A a = A.INSTANCE;
        }
        catch (Throwable t) {
            // IGNORE
        }
    }
   
    public static void main(String[] args) {
        new A();
    }
}