Java 重写泛型类中的equals()方法
我想重写这个类中的equals()方法。我在重写equals()方法时遵循通常的规则,但是我将对象类型转换为我的类类型 但是在我的equals()方法中,我只想在对象属于相同的泛型类型时返回true 如何在equals()方法中检查实例的运行时类型 这是我的密码:Java 重写泛型类中的equals()方法,java,generics,Java,Generics,我想重写这个类中的equals()方法。我在重写equals()方法时遵循通常的规则,但是我将对象类型转换为我的类类型 但是在我的equals()方法中,我只想在对象属于相同的泛型类型时返回true 如何在equals()方法中检查实例的运行时类型 这是我的密码: public class GenericsRunTimeType<T> { private T foo; public GenericsRunTimeType(T foo){ this.foo = foo; }
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;
}
公共类GenericsRunTimeType{
私人T foo ;;
公共泛型RuntimeType(T foo){
this.foo=foo;
}
@凌驾
公共布尔等于(对象obj){
if(this==obj)
返回true;
if(obj==null)
返回false;
如果(getClass()!=obj.getClass())
返回false;
//在此之前,我想测试obj和this是否属于相同的泛型类型
GenericsRunTimeType其他=(GenericsRunTimeType)obj;
如果(其他等于(obj))
返回true;
其他的
返回false;
}
P> >一个选择是使用反射,但我认为这是我的最后一个选择。
另一个选项(我在这里更喜欢)是在构造函数中传递Class
参数,并将其存储在字段中:
private T foo;
private Class<T> clazz;
public GenericsRunTimeType(T foo, Class<T> clazz){
this.foo = foo;
this.clazz = clazz;
}
在您的情况下,您只需检查:
foo.getClass().equals(other.foo.getClass())
这是因为您的类中已经有
T
类的成员。然而,在通常情况下,当您没有这样的成员时,请查看@Rohit Jain所做的回答。(+1)我给出了另一个方向:您真的需要检查类型参数的相等性吗
给定示例中的foo
应该是等式的一部分,通常equals()
方法应该如下所示
public boolean equals(Object obj){
if (this == obj)
return true;
if (obj == null)
return false;
if (!obj instanceof GenericsRunTimeType)
return false;
GenericsRunTimeType other = (GenericsRunTimeType) obj;
return (this.foo.equals(obj.foo)) // !Here
// can be better wrote as foo==obj.foo || (foo != null && foo.equals(obj.foo))
// I wrote in a simpler form just to give you the idea
}
无论这两个foo
是否属于同一类型,通常由foo
的equals()负责处理。如果您不关心这两个foo
是否相等,那么为什么您要关心这两个foo
是否属于同一类型
当然还有其他选择,如其他答案所建议的,您可以从
foo
中获取类型,然后比较它们,或者传入另一个类
对象。然而,我认为在大多数情况下可能没有必要。它是否没有给出期望的结果?但是,如果(getClass()!=obj.getClass()),仅仅因为foo.getClass().equals(other.foo.getClass())
并不意味着类型参数是相同的。相反,类型参数可能是相同的,foo.getClass().equals(other.foo.getClass())
可能不是真的。
public boolean equals(Object obj){
if (this == obj)
return true;
if (obj == null)
return false;
if (!obj instanceof GenericsRunTimeType)
return false;
GenericsRunTimeType other = (GenericsRunTimeType) obj;
return (this.foo.equals(obj.foo)) // !Here
// can be better wrote as foo==obj.foo || (foo != null && foo.equals(obj.foo))
// I wrote in a simpler form just to give you the idea
}