How to load nested classes in Java?

2019-02-06 02:33发布

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?

3条回答
你好瞎i
2楼-- · 2019-02-06 02:37

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();
    }
}
查看更多
闹够了就滚
3楼-- · 2019-02-06 02:41

You need to use the fully qualified class name, i.e. yourpackage.CheckInnerStatic$Test (assuming you defined a package, otherwise skip that part).

查看更多
唯我独甜
4楼-- · 2019-02-06 02:43
Class innerClass = Class.forName("com.foo.OuterClass$InnerClass");
查看更多
登录 后发表回答