Skip to content

Commit d444a9e

Browse files
authored
Only remove imports when method select changes (#6277)
1 parent 9b1a93f commit d444a9e

2 files changed

Lines changed: 36 additions & 4 deletions

File tree

rewrite-java-test/src/test/java/org/openrewrite/java/UseStaticImportTest.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import org.openrewrite.DocumentExample;
2020
import org.openrewrite.Issue;
2121
import org.openrewrite.test.RewriteTest;
22+
import org.openrewrite.test.TypeValidation;
2223

2324
import static org.openrewrite.java.Assertions.java;
2425

@@ -426,4 +427,36 @@ void sample() {
426427
)
427428
);
428429
}
430+
431+
@Issue("https://github.com/openrewrite/rewrite/issues/6275")
432+
@Test
433+
void shouldNotRemoveUsedStaticImport() {
434+
rewriteRun(
435+
spec -> spec.recipe(new UseStaticImport("java.util.Collections *(..)"))
436+
.typeValidationOptions(TypeValidation.all().identifiers(false).methodInvocations(false)),
437+
java(
438+
"""
439+
import java.util.Collections;
440+
import java.util.Set;
441+
442+
class Test extends TypeNotFound {
443+
void test() {
444+
Set<String> set = Collections.unmodifiableSet(newHashSetFromSuperType());
445+
}
446+
}
447+
""",
448+
"""
449+
import java.util.Set;
450+
451+
import static java.util.Collections.unmodifiableSet;
452+
453+
class Test extends TypeNotFound {
454+
void test() {
455+
Set<String> set = unmodifiableSet(newHashSetFromSuperType());
456+
}
457+
}
458+
"""
459+
)
460+
);
461+
}
429462
}

rewrite-java/src/main/java/org/openrewrite/java/UseStaticImport.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,11 +88,10 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
8888
return m;
8989
}
9090

91-
JavaType.FullyQualified receiverType = m.getMethodType().getDeclaringType();
92-
maybeRemoveImport(receiverType);
93-
maybeAddImport(receiverType.getFullyQualifiedName(), m.getSimpleName(), false);
94-
9591
if (m.getSelect() != null) {
92+
JavaType.FullyQualified receiverType = m.getMethodType().getDeclaringType();
93+
maybeRemoveImport(receiverType);
94+
maybeAddImport(receiverType.getFullyQualifiedName(), m.getSimpleName(), false);
9695
return m.withSelect(null).withName(m.getName().withPrefix(m.getSelect().getPrefix()));
9796
}
9897
}

0 commit comments

Comments
 (0)