用反射创建内部类对象 [英] creating inner class objects with reflection
问题描述
如何使用反射创建内部类对象? Inner和Outer类都有默认构造函数,不带参数
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?
}
}
推荐答案
< a href =http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Constructor.html#newInstance-java.lang.Object...- =nofollow> 如果构造函数的声明类是非静态上下文中的内部类,则构造函数的第一个参数需要是封闭实例;请参阅 Java™语言规范的第15.9.3节。
"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."
这意味着您永远不能使用 Class.newInstance
构建内部类;相反,您必须使用带有单个 Outer
实例的构造函数。下面是一些演示其用法的示例代码:
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));
}
}
(请注意,在标准Java术语中,内部类总是非静态的。静态成员类称为嵌套类。)
(Note that in standard Java terminology, an inner class is always non-static. A static member class is called a nested class.)
这篇关于用反射创建内部类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!