Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load nested classes in Java?

I have the following java code:

public class CheckInnerStatic {

private static class Test {
    static {
        System.out.println("Static block initialized");
    }
    public Test () {
        System.out.println("Constructor called");
    }
}

    public static void main (String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        System.out.println("Inside main");
        Class.forName("Test");    // Doesn't work, gives ClassNotFoundException
        //Test test = new Test();   // Works fine
    }
}

Why doesn't the class.forName("Test") work here while the next line works fine?

like image 813
Vivek Avatar asked Apr 29 '11 06:04

Vivek


1 Answers

Use Outer$Nested (regardless if nested class is static or not)

public class CheckInnerStatic {

    private static class Test {
    static {
        System.out.println("Static block initialized");
    }
    public Test () {
        System.out.println("Constructor called");
    }
}

    public static void main (String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        System.out.println("Inside main");
        Class<?> cls = Class.forName("CheckInnerStatic$Test");
        //Test test = new Test();
    }
}
like image 95
MeBigFatGuy Avatar answered Oct 02 '22 04:10

MeBigFatGuy