泛型和instanceof-java

泛型和instanceof-java,java,generics,instanceof,Java,Generics,Instanceof,好的,这是我的类,它封装了一个对象,并将等于和的字符串委托给这个对象,为什么我不能使用 public class Leaf<L> { private L object; /** * @return the object */ public L getObject() { return object; } /** * @param object the object to set */

好的,这是我的类,它封装了一个对象,并将等于和的字符串委托给这个对象,为什么我不能使用

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();
    }
}
公共类叶
{
私人物品;
/**
*@返回对象
*/
公共L getObject(){
返回对象;
}
/**
*@param object要设置的对象
*/
公共无效集合对象(L对象){
this.object=对象;
}
公共布尔等于(对象其他)
{
如果(叶的其他实例)/-->此行出错
{
叶o=(叶)其他;
返回此.getObject().equals(o.getObject());
}
返回false;
}
公共字符串toString()
{
返回object.toString();
}
}
我怎样才能让它工作?? 谢谢

因为您只能将
instanceof
与一起使用。(一个直观的解释是,
instanceof
是在运行时进行计算的,但类型参数在编译过程中被删除(“擦除”)

以下是泛型常见问题解答中的一个好条目:


泛型信息实际上在编译时被删除,在运行时不存在。这就是所谓的类型擦除。在引擎盖下,所有的叶子对象实际上都变成了叶子的等价物,并在必要时添加了额外的投射


因此,运行时无法区分Leaf和Leaf之间的差异,因此无法进行instanceof测试。

我遇到了类似的问题,并通过使用反射解决了它,如下所示:

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();
    }
}
公共类叶
{
私人物品;
/**
*@返回对象
*/
公共L getObject(){
返回对象;
}
/**
*@param object要设置的对象
*/
公共无效集合对象(L对象){
this.object=对象;
}
公共布尔等于(对象其他)
{
如果(叶的其他实例)/-->任何类型的叶
{
叶o=(叶)其他;
L t1=this.getObject();//假定它不是null
Object t2=o.getObject();//我们仍然不确定类型
返回t1.getClass().isInstance(t2)和
t1.equals((Leaf)t2);//只有当t2是同一类型时,我们才能得到这里
}
返回false;
}
公共字符串toString()
{
返回object.toString();
}
}

也许你的意思是你不能使用Instanceofs,那么可能的修复方法是使用它???public boolean equals(Object other){if(Leaf的其他实例){Leaf o=(Leaf)other;返回this.getObject().equals(o.getObject());}返回false;}如果要强调
Leaf
是泛型的,您可以使用Leaf的
其他实例
@fredcrs:这是Eclipse将生成的代码,所以我认为这没问题