我想覆盖此类中的equals()方法。我遵循通常的规则,同时重写equals()方法,但我将对象转换为我的类类型覆盖泛型类中的equals()方法
但在我的equals()方法中,我只想在对象是相同泛型类型时才返回true。
如何在我的equals()方法中检查实例的运行时类型?
这里是我的代码:
public class GenericsRunTimeType<T> {
private T foo;
public GenericsRunTimeType(T foo){
this.foo = foo;
}
@Override
public boolean equals(Object obj){
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
// Before doing this I want to test if obj and this are of the same generic type
GenericsRunTimeType other = (GenericsRunTimeType) obj;
if(other.equals(obj))
return true;
else
return false;
}
}
它没有给出想要的结果吗? if(getClass()!= obj.getClass()) –