Skip to content

Commit 927f25d

Browse files
authored
Skip InstanceOfPatternMatch for try-with-resources casts (#847)
1 parent 4ded8a7 commit 927f25d

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

src/main/java/org/openrewrite/staticanalysis/InstanceOfPatternMatch.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,8 @@ public void registerTypeCast(J.TypeCast typeCast, Cursor cursor) {
198198
for (Iterator<?> it = cursor.getPath(); it.hasNext(); ) {
199199
Object next = it.next();
200200
if (validContexts.contains(next)) {
201-
if (isAcceptableTypeCast(typeCast.getType()) && isTheSameAsOtherTypeCasts(typeCast, instanceOf) && isAcceptableParentTypeCast(parent)) {
201+
if (isAcceptableTypeCast(typeCast.getType()) && isTheSameAsOtherTypeCasts(typeCast, instanceOf) && isAcceptableParentTypeCast(parent) &&
202+
cursor.firstEnclosing(J.Try.Resource.class) == null) {
202203
if (parent.getValue() instanceof J.VariableDeclarations.NamedVariable &&
203204
!variablesToDelete.containsKey(instanceOf)) {
204205
variablesToDelete.put(instanceOf, new VariableAndTypeTree(parent.getValue(),

src/test/java/org/openrewrite/staticanalysis/InstanceOfPatternMatchTest.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1766,4 +1766,28 @@ Throwable wrap(Throwable cause) {
17661766
), 17)
17671767
);
17681768
}
1769+
1770+
@Issue("https://github.com/openrewrite/rewrite/issues/4173")
1771+
@Test
1772+
void unchangedTryWithResourcesCast() {
1773+
rewriteRun(
1774+
//language=java
1775+
java(
1776+
"""
1777+
import java.io.Closeable;
1778+
1779+
class A {
1780+
void foo(Object object) {
1781+
if (object instanceof Closeable) {
1782+
try (Closeable c = (Closeable) object) {
1783+
System.out.println(c);
1784+
} catch (Exception e) {
1785+
}
1786+
}
1787+
}
1788+
}
1789+
"""
1790+
)
1791+
);
1792+
}
17691793
}

0 commit comments

Comments
 (0)