Generics and instanceof - java

僤鯓⒐⒋嵵緔 提交于 2019-12-05 15:06:34

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:

Generic information is actually removed at compile time and doesn't exist at run time. This is known as type erasure. Under the hood all your Leaf objects actually become the equivalent of Leaf<Object> and additional casts are added where necessary.

Because of this the runtime cannot tell the difference between Leaf<Foo> and Leaf<Bar> and hence an instanceof test is not possible.

I have similar problem and solved it by using reflection like this:

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();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!