泛型和instanceof - java

fre*_*crs 4 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

怎么才能让这个工作?谢谢!

aio*_*obe 10

由于类型擦除,您只能使用instanceof复制类型.(直观的解释是instanceof在运行时评估的内容,但在编译期间删除("擦除")类型参数.)

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

  • 如果你想强调`Leaf`是通用的,你可以使用`其他instanceof Leaf <?>`. (2认同)