[英]JAVA creating instance of nested static class with reflection
我想創建一個帶有反射的嵌套 靜態類的實例。 我有以下代碼:
if (Modifier.isStatic(nestedClass.getModifiers())) {
//TODO - WRITE HERE SOMETHING
} else {
ctor = nestedClass.getDeclaredConstructor(outerClass);
ctor.setAccessible(true);
testInstance = ctor.newInstance(outerInstance);
}
但無法弄清楚在if語句中該怎么做。 一些幫助或建議,將不勝感激。 謝謝。
嵌套的靜態類不需要外部實例,因此請嘗試與else
相同, outerInstance
構造函數的參數中刪除outerClass
和outerInstance
。
ctor = nestedClass.getDeclaredConstructor();//no outer class in argument
ctor.setAccessible(true);
testInstance = ctor.newInstance();//no outer instance in argument
嘗試類似的方法:
Class<MyClass> nestedClass = MyClass.class;
if (Modifier.isStatic(nestedClass.getModifiers())) {
MyClass instance = nestedClass.newInstance();
System.out.println(instance);
}
Output:
MainClass$MyClass@1db9742
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.