2011-04-13 39 views
0

我有一個基類BASE和夫婦繼承類BASE_1,BASE_2 ,, BASE_3。我在代碼BASE測試,但如何發現它指向什麼類:BASE_1,BASE_2或BASE_3?發現什麼繼承類它指向

回答

3
BASE test = getSomeBase(); 

// method 1 
System.out.println(test.getClass().getName()); // prints the classname 

// method 2 
if (test instanceof BASE_1) { 
    // test is a an instance of BASE_1 
} 
3

我不清楚你在問什麼,但你可以使用getClass()方法和instanceof算子。

如果是像

Base b = new Child1(); 
b.getClass();//will give you child1 
3

要查看特定對象的類名,你可以使用:

test.getClass().getName(); 

但你不應該普遍關心,因爲這取決於任何功能你應該在哪些子類中實現這些子類作爲這些子類中的重載(「多態」)函數。

+0

+1「但你不應該普遍關心」 – 2011-04-13 13:37:53

2

您可以使用instanceof檢查特定類型或.getClass()獲得Class對象描述特定的類:用於

Base test = getSomeBaseObject(); 

System.out.println("test is a " + test.getClass().getName()); 
if (test instanceof Base1) { 
    System.out.println("test is a Base1"); 
}