简体   繁体   English

用反射创建内部类对象

[英]creating inner class objects with reflection

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 class{
   }
    public void createO() {
        Outer.Inner ob = new Inner ();//that works
        Inner.class.newInstance(); //<--why does this not compile?
   }
}

"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 ." “如果构造函数的声明类是非静态上下文中的内部类,则构造函数的第一个参数必须是封闭的实例;请参见Java™语言规范的 15.9.3节。”

That means you can never construct an inner class using Class.newInstance ; 这意味着您永远无法使用Class.newInstance构造内部类; instead, you must use the constructor that takes a single Outer instance. 相反,您必须使用带有单个Outer实例的构造函数。 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 .) (请注意,在标准Java术语中, 内部类始终是非静态的。静态成员类称为嵌套类 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM