2011-07-08 74 views
2
String child = "C"; 
Parent p = null; 
try { 
    Class c1 = new Class.forName(child); 
    Constructor co = c1.getConstructor(); 
    // p=co.newInstance(null); //This gives compilatoin error cannot 
    // conver object to Parent 
    // p=(c1.getClass())co.newInstance(null);//also gives cast errror 
    p = (Parent) co.newInstance(null);// this works but it typecasts the 
    // child to Parent 
} catch (Exception e) { 
} 

我在做什麼。Java反射:動態創建類實例並將其分配給父對象

我有從父繼承的多個子類。我正在將子類名稱作爲字符串輸入。

我想實例化Child類的對象並將其分配給Parent。我不想輸入將孩子轉換爲父母。在後面的代碼中,我需要比較兩個Child類。如果我將它轉換爲Parent。我無法區分Child1和Child2。

+0

你如何比較你的child1和child2? – Lynch

+1

你可能想看看[Polymorphism](http://en.wikipedia.org/wiki/Polymorphism_(computer_science))。 –

回答

3

我不認爲你明白「類型轉換」的作用。它對對象本身有絕對沒有影響。使用p = (Parent) t僅對t執行運行時檢查以確保t的類型可指定爲Parent(即,t是-或它是-的子類)。之後,t仍然是Child1或任何其實際類型總是。

使用顯式強制轉換。

1

你可以嘗試這樣的:

Object parent = null; 
String child = String.class.getName(); //not necessary, can just use String.class directly 
Class childClass = Class.forName(child); 
Class parentClass = Object.class; 

if (parentClass.isAssignableFrom(childClass)) { 
    parent = childClass.newInstance(); 
} 

System.out.println("Parent is: " + parent); 
0

即使家長鑄造形式2個不同的孩子

Parent parent1 = (Parent)child1; 
Parent parent2 = (Parent)child2; 

的parent1和parent2是完全不同的基於每個孩子。

您可以將它們打印爲

System.out.println(parent1.getClass().getName()); 
System.out.println(parent2.getClass().getName()); 

看出差別那麼你可以使用的getName()比較它。

我希望這可能有助於達到要求。

Regards,

Charlee Ch。

相關問題