How to load nested classes in Java?

前端 未结 3 1383
悲&欢浪女
悲&欢浪女 2020-12-31 03:37

I have the following java code:

public class CheckInnerStatic {

private static class Test {
    static {
        System.out.println(\"Static block initializ         


        
相关标签:
3条回答
  • 2020-12-31 04:22

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-31 04:23

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

    0 讨论(0)
  • 2020-12-31 04:27
    Class innerClass = Class.forName("com.foo.OuterClass$InnerClass");
    
    0 讨论(0)
提交回复
热议问题