2011-06-29 62 views
2

下面我有FindBugs的錯誤我的「平等」的方法,equals方法覆蓋等於在超類,也有可能對稱

This class defines an equals method that overrides an equals method in a superclass. Both equals methods methods use instanceof in the determination of whether two objects are equal. This is fraught with peril, since it is important that the equals method is symmetrical (in other words, a.equals(b) == b.equals(a)). If B is a subtype of A, and A's equals method checks that the argument is an instanceof A, and B's equals method checks that the argument is an instanceof B, it is quite likely that the equivalence relation defined by these methods is not symmetric.

我不能在這裏發佈的代碼安全violataion。請讓我知道什麼是錯誤?

+2

如果你不張貼一些有代表性的代碼,它將很難看到錯誤... –

+2

他只需要findbugs「錯誤」的解釋。我認爲沒有必要的代碼。 –

回答

9

它說equals()的合同意味着,a.equals(b)是真實的,當且僅當b.equals(a)爲真。

如果B擴展A,在A.equals(Object obj)你可能會有

if !(obj instanceof A) return false; 

B.equals(Object obj)你將有

if !(obj instanceof B) return false; 

這裏是不對稱的:乙品牌的一個實例(b instanceof A)真實,而A的一個實例使得(a instanceof B)爲false。所以這意味着風險比a.equals(b)爲真,並且b.equals(a)爲假。

2

您可以使用類似的結構,以防止此錯誤:

public boolean equals(final Object obj) 
{ 
    if (obj == null || getClass() != obj.getClass()) 
    { 
     return false; 
    } 
// ... 

,而不是

public boolean equals(final Object obj) 
{ 
    if (!(o instanceof UniversalIDDefinition)) 
    { 
     return false; 
    } 
// ... 
0

你可以使用這個太:

if (obj == null || !MyClass.class.isAssignableFrom(obj.getClass())) { 
    return false; 
}