[英]Get Inner Class Instance status
用例類似於下面的代碼。 在另一個類(Outer_Demo)中有一個類(Inner_Demo)。 Inner_class將在外部類私有方法中的某些條件下實例化。
class Outer_Demo {
public Outer_Demo() {
test();
}
// private method of the outer class
private void test() {
Inner_Demo demo;
if(condition)
demo = new Inner_Demo();
}
// inner class
class Inner_Demo {
}
}
main(){
Outer_Demo outer = new Outer_Demo();
// Here I need to check is Inner class got instantiated
// Trying to print the value as below leads to error create
// field/constant Inner_Demo in Outer_Demo
System.out.println(Outer_Demo.Inner_Demo); // outer.Inner_Demo
/* Storing the created instance to Outer_Demo.Inner_Demo
is allowed */
Outer_Demo.Inner_Demo inst = outer.new Inner_Demo();
System.out.println(inst);
}
我需要測試,內部類是否實例化。 我知道以上述方式調用內部類是不正確的。
如果Outer_Demo類的方法測試中的字段演示不是本地/具有類級別訪問,則可能使用了反射。 任何人都可以幫助我理解,有沒有辦法找到內部階級狀態。 任何主題鏈接都是有幫助的。 謝謝。
您可能想要檢查該類的對象是否已實例化。
對於此任務,您應該在Outer_Demo
類中聲明一個Inner_Demo
字段:
class Outer_Demo {
public Outer_Demo() {
test();
}
Inner_Demo innerDemo;
...
現在,每次實例化對象時,都必須為該字段分配一個值:
innerDemo = new Inner_Demo();
最后,當你想檢查對象是否存在時,你就像這樣做:
if (innerDemo == null) {
//object does not exist yet and has to be instantiated
} else {
//object does exist and can be used
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.