如何在Java中加载嵌套类?

2022-09-02 11:35:04

我有以下java代码:

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
    }
}

为什么这里的工作不工作,而下一行工作正常?class.forName("Test")


答案 1

使用(无论嵌套类是否为静态)Outer$Nested

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

答案 2

您需要使用完全限定的类名,即 (假设您定义了一个包,否则请跳过该部分)。yourpackage.CheckInnerStatic$Test


推荐