![](/img/trans.png)
[英]Inner class not able to access outer class member variable which is initialized from a method which internally calls constructor
[英]How can I tell which constructor to use on an inner (member) class?
内部类的反射实例化需要一个带有综合参数的构造函数,即封闭类的实例。 如果内部类是静态的,则没有此类构造函数。
我可以使用Class.isMemberClass()方法告诉一个类是一个内部类,但是我看不到一种确定成员类是否为静态的灵巧方法,这就是我希望弄清楚的方式调用哪个构造函数。
有一个整洁的方法可以告诉吗?
请参阅“ 检查类修饰符”教程。 我觉得有点像
Modifier.isStatic(myClass.getModifiers());
大卫是正确的。 我只是要发表你的意思
内部类的反射实例化需要一个带有综合参数的构造函数,即封闭类的实例。
对于像我这样需要尝试的人:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.