【发布时间】:2013-08-20 21:03:27
【问题描述】:
我想在这个类中重写 equals() 方法。我在覆盖 equals() 方法时遵循通常的规则,但是我将 Object 类型转换为我的类类型
但在我的 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())