Skip to content

Commit

Permalink
RemoveUnusedImports should not remove imports for used nested class…
Browse files Browse the repository at this point in the history
…es (#4479)

* Add testcases for nested imports

* Apply suggestions from code review

* Move the fix to RemoveUnusedImports recipe

* Revert javadoc

* Remove unnecessary cast

---------

Co-authored-by: Tim te Beek <tim@moderne.io>
  • Loading branch information
Laurens-W and timtebeek authored Sep 10, 2024
1 parent 63ce3b3 commit 2236981
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1906,4 +1906,81 @@ public class Bar {
)
);
}

@Issue("https://github.com/openrewrite/rewrite/issues/3283")
@Test
void nestedImport() {
rewriteRun(
java(
"""
package foo;
public interface J {
final class One implements J {}
final class Two implements J {}
final class Three implements J {}
final class Four implements J {}
final class Five implements J {}
final class Six implements J {}
}
"""
),
java(
"""
package bar;
import foo.J;
import foo.J.*;
class Quz {
void test() {
J j = null;
One one = null;
Two two = null;
Three three = null;
Four four = null;
Five five = null;
Six six = null;
}
}
"""
)
);
}

@Issue("https://github.com/openrewrite/rewrite/issues/3283")
@Test
void nestedImportStaticInnerClass() {
rewriteRun(
java(
"""
package com.a.b.c;
public final class ParentBaseClass {
public static abstract class BaseImplClass {
void foo() {
}
}
}
"""
),
java(
"""
import com.a.b.c.ParentBaseClass.*;
public class MyClass extends BaseImplClass {
@Override
public void foo() {
}
}
""",
"""
import com.a.b.c.ParentBaseClass.BaseImplClass;
public class MyClass extends BaseImplClass {
@Override
public void foo() {
}
}
"""
)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon
// add each unfolded import
combinedTypes.stream().map(JavaType.FullyQualified::getClassName).sorted().distinct().forEach(type ->
anImport.imports.add(new JRightPadded<>(elem
.withQualid(qualid.withName(name.withSimpleName(type)))
.withQualid(qualid.withName(name.withSimpleName(type.substring(type.lastIndexOf('.') + 1))))
.withPrefix(Space.format("\n")), Space.EMPTY, Markers.EMPTY))
);

Expand All @@ -236,7 +236,7 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon

changed = true;
} else {
usedWildcardImports.add(elem.getPackageName());
usedWildcardImports.add(elem.getQualid().getTarget().toString());
}
} else if (combinedTypes.stream().noneMatch(c -> {
if ("*".equals(elem.getQualid().getSimpleName())) {
Expand Down

0 comments on commit 2236981

Please sign in to comment.