mirror of
https://github.com/alibaba/p3c.git
synced 2025-10-17 16:44:04 +00:00
This commit is contained in:
@@ -45,8 +45,14 @@ public class WrapperTypeEqualityRule extends AbstractAliRule {
|
||||
// possible elements around "==" are PrimaryExpression or UnaryExpression(e.g. a == -2)
|
||||
List<ASTPrimaryExpression> expressions = node.findChildrenOfType(ASTPrimaryExpression.class);
|
||||
if (expressions.size() == NumberConstants.INTEGER_SIZE_OR_LENGTH_2) {
|
||||
if (NodeUtils.isWrapperType(expressions.get(0)) &&
|
||||
NodeUtils.isWrapperType(expressions.get(1))) {
|
||||
// PMD can not resolve array length type, but only the
|
||||
ASTPrimaryExpression left = expressions.get(0);
|
||||
ASTPrimaryExpression right = expressions.get(1);
|
||||
|
||||
boolean bothArrayLength = isArrayLength(left) && isArrayLength(right);
|
||||
boolean bothWrapperType = NodeUtils.isWrapperType(left) && NodeUtils.isWrapperType(right);
|
||||
|
||||
if (!bothArrayLength && bothWrapperType) {
|
||||
addViolationWithMessage(data, node, "java.oop.WrapperTypeEqualityRule.violation.msg");
|
||||
}
|
||||
}
|
||||
@@ -54,4 +60,9 @@ public class WrapperTypeEqualityRule extends AbstractAliRule {
|
||||
return super.visit(node, data);
|
||||
}
|
||||
|
||||
private boolean isArrayLength(ASTPrimaryExpression expression) {
|
||||
// assume expression like "x.length" is the length of array, field with name "length" may result in misrecognition
|
||||
return "length".equals(expression.jjtGetLastToken().getImage())
|
||||
&& ".".equals(expression.jjtGetFirstToken().getNext().getImage());
|
||||
}
|
||||
}
|
||||
|
@@ -150,4 +150,28 @@
|
||||
<expected-problems>0</expected-problems>
|
||||
<code-ref id="wrong-result-fix" />
|
||||
</test-code>
|
||||
|
||||
<!-- ====================================================================== -->
|
||||
|
||||
<code-fragment id="array-length-equals">
|
||||
<![CDATA[
|
||||
public class Test {
|
||||
public void foo(){
|
||||
Integer[] a;
|
||||
Integer[] b;
|
||||
if (a.length == b.length) {
|
||||
return;
|
||||
};
|
||||
}
|
||||
}
|
||||
]]>
|
||||
</code-fragment>
|
||||
<test-code>
|
||||
<description>array length equals</description>
|
||||
<expected-problems>0</expected-problems>
|
||||
<code-ref id="array-length-equals"/>
|
||||
</test-code>
|
||||
|
||||
<!-- ====================================================================== -->
|
||||
|
||||
</test-data>
|
Reference in New Issue
Block a user