[java] EmptyControlStatement: Fix NPE for concise try-with-resources

This commit is contained in:
Andreas Dangel
2022-05-27 15:04:36 +02:00
parent 0ef01e0fb5
commit 7ed7fc0e42
3 changed files with 24 additions and 1 deletions

View File

@@ -25,6 +25,15 @@ public class ASTResource extends ASTFormalParameter {
return visitor.visit(this, data);
}
public String getName() {
ASTVariableDeclaratorId variableDeclaratorId = getVariableDeclaratorId();
if (variableDeclaratorId != null) {
return variableDeclaratorId.getName();
}
// concise try-with-resources
return getFirstChildOfType(ASTName.class).getImage();
}
// TODO Should we deprecate all methods from ASTFormalParameter?
}

View File

@@ -132,7 +132,7 @@ public class EmptyControlStatementRule extends AbstractJavaRule {
if (resources != null) {
for (ASTResource resource : resources.findDescendantsOfType(ASTResource.class)) {
hasResource = true;
String name = resource.getVariableDeclaratorId().getName();
String name = resource.getName();
if (!JavaRuleUtil.isExplicitUnusedVarName(name)) {
allResourcesIgnored = false;
break;

View File

@@ -106,6 +106,20 @@
]]></code>
</test-code>
<test-code>
<description>empty concise try-with-resource - not ok</description>
<expected-problems>1</expected-problems>
<expected-linenumbers>4</expected-linenumbers>
<code><![CDATA[
import java.io.InputStream;
class X {
void method(InputStream in) {
try (in) {
}
}
}
]]></code>
</test-code>
<test-code>
<description>pos, empty synchronized stmt</description>