2013-08-19 98 views
2

我想覆盖此类中的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; 
} 

}

+2

它没有给出想要的结果吗? if(getClass()!= obj.getClass()) –

回答

5

一种选择是使用反射,但我会认为这是我的最后一招。

另一种选择,我宁愿在这里,是通过在构造函数中Class<T>参数,并将其存储在一个领域:

private T foo; 
private Class<T> clazz; 
public GenericsRunTimeType(T foo, Class<T> clazz){ 
    this.foo = foo; 
    this.clazz = clazz; 
} 

然后在equals方法,做的比较像这样:

if (this.clazz == ((GenericsRunTimeType)obj).clazz) { 
    System.out.println("Same type"); 
} 
7

你的情况,你可以检查:

foo.getClass().equals(other.foo.getClass())

这是因为您班上已有班级T的成员。然而,在你没有这样的成员的情况下,请看@Rohit Jain所做的答案。 (+1)

+0

但是,仅仅因为'foo.getClass()。equals(other.foo.getClass())'并不意味着类型参数是相同的。相反,类型参数可能是相同的,并且'foo.getClass()。equals(other.foo.getClass())'可能不是真的。 – newacct

2

我在给另一个方向:你真的需要检查TYPE PARAMETER的相等吗?

鉴于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来处理。如果你不关心这两个foo是否相等,那么为什么要关心foo是否属于同一类型?

当然,还有其他的选择,比如其他答案所建议的,其中您从foo获得类型,并比较它们或通过另一个Class对象。不过,我认为在大多数情况下可能没有必要。