2014-03-29 65 views
0

所以這是我的問題的上下文。從對象變量中恢復屬性

我創建了一個單鏈表,其節點的屬性是一個Object變量,所以我可以存儲來自不同類的對象。到現在爲止還挺好。

 public class Node 
    { 

     Object data; 
     Node next; 

     public Node(Object data) 
     { 
      this.data=data; 
      this.next=null; 
     } 

[...]  

} 

事情是我不知道如何從存儲的對象中恢復屬性/方法。這個例子。

public class Product 
{ 
    double discount; 
    double price; 

    public double getPrice() { 
     return price; 
    } 

[...] 

幫助。

回答

0

另一種方式,如果你有,你是存儲類型的對象的數量有限(或至少計劃從中獲取屬性)是使用instanceof和類別鑄造

if(node.data instanceof Product){ 
    Product p = (Product) node.data; 
    //Get attributes from products 
else if(node.data instanceof SomethingElse){ 
    SomethingElse p = (SomethingElse) node.data; 
    //Get attributes from somethingElse 
} 
... 
else{ 
    //throw an error or ignore the final case 
}