2010-12-09 119 views
4

好吧,這是我的類,它封裝了一個對象,並委託equals和String爲這個對象,爲什麼我不能使用實例???泛型和java實例 - java

public class Leaf<L> 
{ 
    private L object; 

    /** 
    * @return the object 
    */ 
    public L getObject() { 
     return object; 
    } 

    /** 
    * @param object the object to set 
    */ 
    public void setObject(L object) { 
     this.object = object; 
    } 

    public boolean equals(Object other) 
    { 
     if(other instanceof Leaf<L>) //--->ERROR ON THIS LINE 
     { 
      Leaf<L> o = (Leaf<L>) other; 
      return this.getObject().equals(o.getObject()); 
     } 
     return false; 
    } 

    public String toString() 
    { 
     return object.toString(); 
    } 
} 

我該怎麼做到這一點? 謝謝!

+0

也許你的意思是你不能使用instanceof – dimitrisli 2010-12-09 11:29:36

回答

10

由於type erasure只能使用instanceofreifiable types。 (一個直觀的解釋是:instanceof編譯過程中的東西,在運行時計算,但類型參數被刪除(「擦除」)。)

這裏是一個泛型常見問題一個很好的入門:

+0

SO一個可能的解決將是使用這個??? public boolean equals(Object other) if(other other of leaf) {oo =(Leaf)other; return this.getObject()。equals(o.getObject()); } return false; } – fredcrs 2010-12-09 11:29:55

2

通用信息實際上在編譯時被刪除,並且在運行時不存在。這被稱爲類型擦除。在引擎蓋下,所有的葉子對象實際上成爲葉子<對象>的等同物,並且在必要時添加額外的蒙版。

因此,運行時無法區分葉<Foo>和葉<柱>,因此測試實例是不可能的。

2

我有類似的問題,通過使用這樣的反射解決它:

public class Leaf<L> 
{ 
    private L object; 

    /** 
    * @return the object 
    */ 
    public L getObject() { 
     return object; 
    } 

    /** 
    * @param object the object to set 
    */ 
    public void setObject(L object) { 
     this.object = object; 
    } 

    public boolean equals(Object other) 
    { 
     if(other instanceof Leaf) //--->Any type of leaf 
     { 
      Leaf o = (Leaf) other; 
      L t1 = this.getObject(); // Assume it not null 
      Object t2 = o.getObject(); // We still not sure about the type 
      return t1.getClass().isInstance(t2) && 
       t1.equals((Leaf<L>)t2); // We get here only if t2 is same type 
     } 
     return false; 
    } 

    public String toString() 
    { 
     return object.toString(); 
    } 
}