本文介绍了泛型和instanceof - java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  public class Leaf< L> 
{
private L对象;
$ b $ **
* @返回对象
* /
public L getObject(){
return object;
}

/ **
* @param对象设置对象
* /
public void setObject(L object){
this.object = object;
}

public boolean equals(Object other)
{
if(其他实例的Leaf< L>)// --->本行错误
{
Leaf< L> o =(Leaf L)其他;
返回this.getObject()。equals(o.getObject());
}
返回false;
}

public String toString()
{
return object.toString();
}
}

我该如何解决这个问题?
Thanks!

解决方案

由于您只能将 instanceof 与。 (一个直观的解释是, instanceof 是在运行时计算的,但是在编译过程中类型参数被删除(擦除)。



以下是泛型常见问题解答中的一个不错的入口:




OK this is my class, it encapsulates an object, and delegates equals and to String to this object, why I can´t use instance of???

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

how can I get this to work??Thanks!

解决方案

Due to type erasure you can only use instanceof with reifiable types. (An intuitive explanation is that instanceof is something that is evaluated at runtime, but the type-parameters are removed ("erased") during compilation.)

Here is a good entry in a Generics FAQ:

这篇关于泛型和instanceof - java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 10:03