[java] CompareObjectsWithEquals: only allow this with equals (#2934)
This commit is contained in:
@ -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>
|
||||
|
@ -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>
|
||||
|
Reference in New Issue
Block a user