[java] CloseResource - fix class cast exception with pattern matching
This commit is contained in:
2 files changed
+22
-2
No files matched your search
+10
-2
@@ -35,6 +35,7 @@ import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTNullLiteral;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTPatternExpression;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTStatement;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTTryStatement;
|
||||
@@ -214,8 +215,15 @@ public class CloseResourceRule extends AbstractJavaRule {
|
||||
}
|
||||
|
||||
private TypeNode getDeclaredTypeOfVariable(ASTVariableDeclaratorId var) {
|
||||
ASTLocalVariableDeclaration localVar = (ASTLocalVariableDeclaration) var.getParent().getParent();
|
||||
return localVar.getTypeNode(); // note: can be null, if type is inferred (var)
|
||||
JavaNode exprOrDecl = var.getParent().getParent();
|
||||
if (exprOrDecl instanceof ASTLocalVariableDeclaration) {
|
||||
ASTLocalVariableDeclaration localVar = (ASTLocalVariableDeclaration) exprOrDecl;
|
||||
return localVar.getTypeNode(); // note: can be null, if type is inferred (var)
|
||||
} else if (exprOrDecl instanceof ASTPatternExpression) {
|
||||
ASTPatternExpression pattern = (ASTPatternExpression) exprOrDecl;
|
||||
return pattern.descendants(TypeNode.class).first();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private TypeNode getRuntimeTypeOfVariable(ASTVariableDeclaratorId var) {
|
||||
|
||||
+12
@@ -1984,6 +1984,18 @@ public class CloseResourceForEachLoop {
|
||||
}
|
||||
|
||||
private InputStream[] getStreams() { return null; }
|
||||
}
|
||||
]]></code>
|
||||
</test-code>
|
||||
|
||||
<test-code>
|
||||
<description>ClassCastException with pattern matching</description>
|
||||
<expected-problems>0</expected-problems>
|
||||
<code><![CDATA[
|
||||
public class TypePattern {
|
||||
static boolean doStuff(Object obj) {
|
||||
return obj instanceof Integer myIntVar && myIntVar > 0;
|
||||
}
|
||||
}
|
||||
]]></code>
|
||||
</test-code>
|
||||
|
||||
Reference in new issue
Block a user