[java] CloseResource: support try-with-resources

This commit is contained in:
Andreas Dangel
2019-06-22 19:01:24 +02:00
parent 1e03ae5c06
commit 86ce57ca3c
2 changed files with 36 additions and 3 deletions

View File

@ -32,6 +32,7 @@ import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix;
import net.sourceforge.pmd.lang.java.ast.ASTReferenceType;
import net.sourceforge.pmd.lang.java.ast.ASTResourceSpecification;
import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement;
import net.sourceforge.pmd.lang.java.ast.ASTStatementExpression;
import net.sourceforge.pmd.lang.java.ast.ASTTryStatement;
@ -157,10 +158,12 @@ public class CloseResourceRule extends AbstractJavaRule {
if (var.hasInitializer()) {
// figure out the runtime type. If the variable is initialized, take the type from there
TypeNode runtimeType = var.getInitializer().getFirstChildOfType(ASTExpression.class);
if (runtimeType != null && !isAllowedResourceType(runtimeType)) {
ids.put(var.getVariableId(), runtimeType);
if (runtimeType != null && runtimeType.getType() != null) {
type = runtimeType;
}
} else {
}
if (!isAllowedResourceType(type)) {
ids.put(var.getVariableId(), type);
}
}
@ -358,6 +361,15 @@ public class CloseResourceRule extends AbstractJavaRule {
if (closed) {
break;
}
} else if (t.isTryWithResources()) {
// maybe the variable is used as a resource
List<ASTName> names = t.getFirstChildOfType(ASTResourceSpecification.class).findDescendantsOfType(ASTName.class);
for (ASTName potentialUsage : names) {
if (potentialUsage.hasImageEqualTo(variableToClose)) {
closed = true;
break;
}
}
}
}

View File

@ -893,4 +893,25 @@ public class Foo {
}
]]></code>
</test-code>
<test-code>
<description>closed with try-with-resources</description>
<expected-problems>0</expected-problems>
<code><![CDATA[
import java.io.*;
public class Foo {
public int bar() {
InputStream inputStream = getInputStreamFromSomewhere();
if (inputStream != null) {
try (InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8")) {
char c = reader.read();
return c;
}
}
return -1;
}
}
]]></code>
</test-code>
</test-data>