creating inner class objects with reflection

后端 未结 1 976
情歌与酒
情歌与酒 2021-01-28 18:51

How do you create an inner class object with reflection? Both Inner and Outer classes have default constructors that take no parameters

Outer class {
    Inner c         


        
相关标签:
1条回答
  • 2021-01-28 19:36

    "If the constructor's declaring class is an inner class in a non-static context, the first argument to the constructor needs to be the enclosing instance; see section 15.9.3 of The Java™ Language Specification."

    That means you can never construct an inner class using Class.newInstance; instead, you must use the constructor that takes a single Outer instance. Here's some example code that demonstrates its use:

    class Outer {
        class Inner {
            @Override
            public String toString() {
                return String.format("#<Inner[%h] outer=%s>", this, Outer.this);
            }
        }
    
        @Override
        public String toString() {
            return String.format("#<Outer[%h]>", this);
        }
    
        public Inner newInner() {
            return new Inner();
        }
    
        public Inner newInnerReflect() throws Exception {
            return Inner.class.getDeclaredConstructor(Outer.class).newInstance(this);
        }
    
        public static void main(String[] args) throws Exception {
            Outer outer = new Outer();
            System.out.println(outer);
            System.out.println(outer.newInner());
            System.out.println(outer.newInnerReflect());
            System.out.println(outer.new Inner());
            System.out.println(Inner.class.getDeclaredConstructor(Outer.class).newInstance(outer));
        }
    }
    

    (Note that in standard Java terminology, an inner class is always non-static. A static member class is called a nested class.)

    0 讨论(0)
提交回复
热议问题