2010-12-09 6 views
4

OK이 클래스는 클래스이며, 객체를 캡슐화하고, 위임자와이 객체에 대한 String을 위임합니다. 왜 인스턴스를 사용할 수 없습니까?Generics and instanceof - 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

답변

10

type erasure으로 인해 instanceofreifiable types 만 사용할 수 있습니다. (직관적 인 설명은 컴파일시) instanceof 런타임에 평가 뭔가이지만, 형식 매개 변수 "삭제"(제거되는 것입니다.) 여기

는 제네릭 자주 묻는 질문에 좋은 항목입니다 :

+0

는 SO 가능한 수정이를 사용하는 것 ??? public boolean equals (Object other) { if (other instanceof Leaf) { 리프 o = (리프) 기타; this.getObject(). equals (o.getObject());를 반환합니다. } false를 반환합니다. } – fredcrs

+0

충분하다면, 그렇습니다. – aioobe

+2

'Leaf'가 일반적이라고 강조하고 싶다면'other instanceof Leaf '를 사용할 수 있습니다. – musiKk

2

일반 정보는 실제로 컴파일 타임에 제거되며 런타임에 존재하지 않습니다. 이를 유형 삭제라고합니다. 후드 아래의 모든 리프 오브젝트는 실제로 리프 < 오브젝트 >과 같으며 필요한 경우 추가 캐스트가 추가됩니다. 이 때문에

리프 < 푸 > 리프 < 바 > 따라서 테스트의 인스턴스 간의 차이를 구별 할 수없는 실행 불가능하다.

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(); 
    } 
}