[java] CompareObjectsWithEquals: only allow this with equals (#2934)

This commit is contained in:
Andreas Dangel
2020-12-04 18:21:11 +01:00
parent fcbccbce43
commit 7f299c4f6c
2 changed files with 11 additions and 3 deletions

View File

@ -1114,7 +1114,10 @@ Use equals() to compare object references; avoid comparing them with ==.
[not(pmd-java:typeIs('java.lang.Enum'))]
[not(pmd-java:typeIs('java.lang.Class'))]) = 2
]
[not(PrimaryExpression[PrimaryPrefix/@ThisModifier = true()][not(PrimarySuffix)])]
[not(PrimaryExpression[PrimaryPrefix/@ThisModifier = true()]
[not(PrimarySuffix)]
[ancestor::MethodDeclaration[@Name = 'equals']])
]
]]>
</value>
</property>

View File

@ -294,7 +294,8 @@ public class ClassWithFields {
<test-code>
<description>#2934 this and class should be ignored</description>
<expected-problems>0</expected-problems>
<expected-problems>1</expected-problems>
<expected-linenumbers>16</expected-linenumbers>
<code><![CDATA[
package net.sourceforge.pmd.lang.java.rule.errorprone.compareobjectswithequals;
@ -302,13 +303,17 @@ public class ClassWithFields {
private Object a;
private Object b;
void test(Object o) {
public boolean equals(Object o) {
if (this == o) { } // should be allowed, since this is a often used pattern in Object::equals.
// comparing class instances is ok
if (o.getClass() == a.getClass()) { }
if (this.getClass() == this.a.getClass()) { }
if (Object.class == a.getClass()) { }
}
void test(Object o) {
if (this == o) { } // this is not allowed here, only in equals
}
}
]]></code>
</test-code>