Skip to content

Commit e1f6696

Browse files
SONARJAVA-5444 Handle case of Reader.of for try-with-resources
1 parent f66aa35 commit e1f6696

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

java-checks/src/main/java/org/sonar/java/checks/TryWithResourcesCheck.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,11 @@ public class TryWithResourcesCheck extends IssuableSubscriptionVisitor implement
4242
MethodMatchers.create().ofTypes("java.net.http.HttpClient").names("newHttpClient").addWithoutParametersMatcher().build()
4343
);
4444

45+
private static final MethodMatchers AUTOCLOSEABLE_FACTORY_MATCHER =
46+
MethodMatchers.create().ofSubTypes("java.io.Reader")
47+
.names("of")
48+
.addParametersMatcher("java.lang.CharSequence").build();
49+
4550
private final Deque<TryStatementTree> withinTry = new LinkedList<>();
4651
private final Deque<List<Tree>> toReport = new LinkedList<>();
4752

@@ -78,7 +83,8 @@ public void visitNode(Tree tree) {
7883

7984
private static boolean isNewAutocloseableOrBuilder(Tree tree, JavaFileScannerContext context) {
8085
return (tree instanceof NewClassTree newClass && newClass.symbolType().isSubtypeOf("java.lang.AutoCloseable")) ||
81-
(context.getJavaVersion().isJava21Compatible() && tree instanceof MethodInvocationTree mit && AUTOCLOSEABLE_BUILDER_MATCHER.matches(mit));
86+
(context.getJavaVersion().isJava21Compatible() && tree instanceof MethodInvocationTree mit && AUTOCLOSEABLE_BUILDER_MATCHER.matches(mit))||
87+
(tree instanceof MethodInvocationTree mit2 && AUTOCLOSEABLE_FACTORY_MATCHER.matches(mit2));
8288
}
8389

8490
private static boolean isFollowedByTryWithFinally(Tree tree) {

0 commit comments

Comments
 (0)