开发者

How to load nested classes in Java?

开发者 https://www.devze.com 2023-03-01 06:39 出处:网络
I have the f开发者_运维百科ollowing java code: public class CheckInnerStatic { private static class Test {

I have the f开发者_运维百科ollowing 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?


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();
    }
}


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


Class innerClass = Class.forName("com.foo.OuterClass$InnerClass");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号