【发布时间】:2013-10-07 17:13:19
【问题描述】:
内部类的反射实例化需要一个带有综合参数的构造函数,即封闭类的实例。如果内部类是静态的,那么就没有这样的构造函数。
我可以使用Class.isMemberClass() 方法判断一个类是一个内部类,但是我看不到一种确定成员类是否为静态的简洁方法,这就是我所期望的找出要调用的构造函数。
有没有巧妙的方法来分辨?
【问题讨论】:
标签: java reflection inner-classes
内部类的反射实例化需要一个带有综合参数的构造函数,即封闭类的实例。如果内部类是静态的,那么就没有这样的构造函数。
我可以使用Class.isMemberClass() 方法判断一个类是一个内部类,但是我看不到一种确定成员类是否为静态的简洁方法,这就是我所期望的找出要调用的构造函数。
有没有巧妙的方法来分辨?
【问题讨论】:
标签: java reflection inner-classes
请参阅Examining Class Modifiers 教程。我觉得有点像
Modifier.isStatic(myClass.getModifiers());
【讨论】:
David is correct.我只是要发布你的意思
内部类的反射实例化需要一个构造函数 接受一个综合参数,即封闭类的实例。
对于像我这样需要尝试的人:
public class Outer {
public String value = "outer";
public static void main(String[] args) throws Exception {
int modifiers = StaticNested.class.getModifiers();
System.out.println("StaticNested is static: " + Modifier.isStatic(modifiers));
modifiers = Inner.class.getModifiers();
System.out.println("Inner is static: " + Modifier.isStatic(modifiers));
Constructor constructor = Inner.class.getConstructors()[0]; // get the only one
Inner inner = (Inner) constructor.newInstance(new Outer()); // the constructor doesn't actually take arguments
}
public static class StaticNested {
}
public class Inner {
public Inner() {
System.out.println(Outer.this.value);
}
}
}
打印
StaticNested is static: true
Inner is static: false
outer
【讨论】: