4

好的,这是我的类,它封装了一个对象,并将 equals 和 String 委托给这个对象,为什么我不能使用实例???

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

我怎样才能让它工作?谢谢!

4

3 回答 3

10

由于类型擦除,您只能instanceofreifiable types一起使用。(直观的解释是,instanceof这是在运行时评估的,但类型参数在编译期间被删除(“擦除”)。)

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

于 2010-12-09T11:27:39.657 回答
2

通用信息实际上在编译时被删除并且在运行时不存在。这称为类型擦除。在引擎盖下,您的所有 Leaf 对象实际上都等效于 Leaf<Object> 并且在必要时添加了额外的强制转换。

因此,运行时无法区分 Leaf<Foo> 和 Leaf<Bar> ,因此无法进行 instanceof 测试。

于 2010-12-09T11:53:27.013 回答
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();
    }
}
于 2013-05-26T18:26:25.510 回答