泛型和instanceof - java

时间:2010-12-09 11:26:40

标签: java generics instanceof

好的这是我的类,它封装了一个对象,并将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();
    }
}

我怎样才能让这个工作? 谢谢!

3 个答案:

答案 0 :(得分:10)

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

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

答案 1 :(得分:2)

通用信息实际上是在编译时删除的,并且在运行时不存在。这被称为类型擦除。在引擎盖下,你所有的Leaf对象实际上都相当于Leaf&lt; Object&gt;并在必要时添加额外的演员阵容。

因此,运行时无法区分Leaf&lt; Foo&gt;之间的差异。和叶&lt; Bar&gt;因此无法进行测试。

答案 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();
    }
}
相关问题