@ -14,6 +14,7 @@ import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTIfStatement;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTInitializer;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTStatementExpression;
|
||||
@ -119,6 +120,12 @@ public class SingularFieldRule extends AbstractLombokAwareRule {
|
||||
break; // Optimization
|
||||
}
|
||||
|
||||
if (location.getFirstParentOfType(ASTLambdaExpression.class) != null) {
|
||||
// This usage is inside a lambda expression
|
||||
violation = false;
|
||||
break; // Optimization
|
||||
}
|
||||
|
||||
Node method = location.getFirstParentOfType(ASTMethodDeclaration.class);
|
||||
if (method == null) {
|
||||
method = location.getFirstParentOfType(ASTConstructorDeclaration.class);
|
||||
|
@ -569,4 +569,40 @@ public class MyClass {
|
||||
}
|
||||
]]></code>
|
||||
</test-code>
|
||||
|
||||
|
||||
<test-code>
|
||||
<description>#177 [java] SingularField with lambdas as final fields</description>
|
||||
<expected-problems>0</expected-problems>
|
||||
<code><![CDATA[
|
||||
/** Dummy class. */
|
||||
public final class Test {
|
||||
private Timer timer1;
|
||||
private Timer timer2;
|
||||
|
||||
/** Dummy constructor. */
|
||||
public Timer() {
|
||||
this.timer1 = new Timer(0, e -> {
|
||||
// do nothing for now
|
||||
});
|
||||
this.timer2 = new Timer(0, e -> {
|
||||
// do nothing for now
|
||||
});
|
||||
}
|
||||
|
||||
/** Use a lambda expression to reference timer1 -- triggers SingularField error. */
|
||||
private final Runnable play1 = () -> {
|
||||
this.timer1.start();
|
||||
};
|
||||
|
||||
/** Use an anonymous class to reference timer2 -- no error. */
|
||||
private final Runnable play2 = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
this.timer2.start();
|
||||
}
|
||||
};
|
||||
}
|
||||
]]></code>
|
||||
</test-code>
|
||||
</test-data>
|
||||
|
Reference in New Issue
Block a user