![](/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.