內部類的反射實例化需要一個構造函數,該構造函數接受一個合成參數,即封閉類的實例。如果內部類是靜態的,那麼就沒有這樣的構造函數。如何判斷在內部(成員)類上使用哪個構造函數?
我可以告訴大家,一類是使用Class.isMemberClass()方法的內部類,但我看不到確定的成員類是否是靜態或沒有,這是我怎麼會希望弄清楚的一種巧妙的方法要調用哪個構造函數。
有沒有一種簡潔的方式來說明?
內部類的反射實例化需要一個構造函數,該構造函數接受一個合成參數,即封閉類的實例。如果內部類是靜態的,那麼就沒有這樣的構造函數。如何判斷在內部(成員)類上使用哪個構造函數?
我可以告訴大家,一類是使用Class.isMemberClass()方法的內部類,但我看不到確定的成員類是否是靜態或沒有,這是我怎麼會希望弄清楚的一種巧妙的方法要調用哪個構造函數。
有沒有一種簡潔的方式來說明?
查看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
快速,準確,直接的。非常感謝。 – Brabster