creating inner class objects with reflection

故事扮演 提交于 2019-12-02 12:44:29

"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.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!