问题
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!
回答1:
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?
回答2:
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.
回答3:
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();
}
}
来源:https://stackoverflow.com/questions/4397660/generics-and-instanceof-java