Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 553
fredcrs Avatar asked Dec 09 '22 12:12

fredcrs


1 Answers

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:

  • Which types can or must not appear as target type in an instanceof expression?
like image 74
aioobe Avatar answered Dec 22 '22 00:12

aioobe