From 989faff56f0d94b1fb9d66a8e962e9f8e4077d89 Mon Sep 17 00:00:00 2001 From: Hoan Nguyen Date: Fri, 10 May 2024 00:39:41 -0700 Subject: [PATCH] Fix bug in `InstanceOfPatternMatch` getting the variable name from the name of a nested class (#291) Co-authored-by: Hoan Nguyen --- .../InstanceOfPatternMatch.java | 4 +-- .../InstanceOfPatternMatchTest.java | 35 +++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/openrewrite/staticanalysis/InstanceOfPatternMatch.java b/src/main/java/org/openrewrite/staticanalysis/InstanceOfPatternMatch.java index 0364fba44..35cc9e506 100644 --- a/src/main/java/org/openrewrite/staticanalysis/InstanceOfPatternMatch.java +++ b/src/main/java/org/openrewrite/staticanalysis/InstanceOfPatternMatch.java @@ -364,9 +364,7 @@ public String variableName(@Nullable JavaType type) { return name; } else if (type instanceof JavaType.FullyQualified) { String className = ((JavaType.FullyQualified) type).getClassName(); - if (className.indexOf('.') > 0) { - className = className.substring(className.lastIndexOf('.')); - } + className = className.substring(className.lastIndexOf('.') + 1); String baseName = null; switch (style) { case SHORT: diff --git a/src/test/java/org/openrewrite/staticanalysis/InstanceOfPatternMatchTest.java b/src/test/java/org/openrewrite/staticanalysis/InstanceOfPatternMatchTest.java index 0d29e191f..c0b668e0c 100644 --- a/src/test/java/org/openrewrite/staticanalysis/InstanceOfPatternMatchTest.java +++ b/src/test/java/org/openrewrite/staticanalysis/InstanceOfPatternMatchTest.java @@ -221,6 +221,41 @@ void test(Object o) { ); } + @Test + void conflictingVariableOfNestedType() { + rewriteRun( + //language=java + java( + """ + import java.util.Map; + + public class A { + void test(Object o) { + Map.Entry entry = null; + if (o instanceof Map.Entry) { + entry = (Map.Entry) o; + } + System.out.println(entry); + } + } + """, + """ + import java.util.Map; + + public class A { + void test(Object o) { + Map.Entry entry = null; + if (o instanceof Map.Entry entry1) { + entry = entry1; + } + System.out.println(entry); + } + } + """ + ) + ); + } + @Issue("https://github.com/openrewrite/rewrite/issues/2787") @Disabled @Test