简体   繁体   中英

Generics and instanceof - java

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:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM