Skip to content

Commit

Permalink
fixed inner class (#3646)
Browse files Browse the repository at this point in the history
* fixed inner class

* Don't add imports for nested types in same CU

---------

Co-authored-by: Knut Wannheden <knut@moderne.io>
  • Loading branch information
Joan Viladrosa and knutwannheden authored Oct 26, 2023
1 parent 494c691 commit 3a85771
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -1765,4 +1765,41 @@ public void test(String s) {
)
);
}

@Test
void doesNotModifyInnerClassesIfIgnoreDefinitionTrue() {
rewriteRun(
spec -> spec.recipe(new ChangeType("Test.InnerA", "Test.InnerB", true)),
java(
"""
public class Test {
private class InnerA {
}
private class InnerB {
}
public void test(String s) {
InnerA a = new InnerA();
}
}
""",
"""
public class Test {
private class InnerA {
}
private class InnerB {
}
public void test(String s) {
InnerB a = new InnerB();
}
}
"""
)
);

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ private void addImport(JavaType.FullyQualified owningClass) {
JavaType.FullyQualified fullyQualifiedTarget = TypeUtils.asFullyQualified(targetType);
if (fullyQualifiedTarget != null) {
JavaType.FullyQualified owningClass = fullyQualifiedTarget.getOwningClass();
if (!(owningClass != null && topLevelClassnames.contains(getTopLevelClassName(fullyQualifiedTarget).getFullyQualifiedName()))) {
if (!topLevelClassnames.contains(getTopLevelClassName(fullyQualifiedTarget).getFullyQualifiedName())) {
if (owningClass != null && !"java.lang".equals(fullyQualifiedTarget.getPackageName())) {
addImport(owningClass);
}
Expand Down Expand Up @@ -259,6 +259,11 @@ public J visitFieldAccess(J.FieldAccess fieldAccess, ExecutionContext ctx) {

@Override
public J visitIdentifier(J.Identifier ident, ExecutionContext ctx) {
// Do not modify the identifier if it's on a inner class definition.
if (Boolean.TRUE.equals(ignoreDefinition) && getCursor().getParent() != null &&
getCursor().getParent().getValue() instanceof J.ClassDeclaration) {
return super.visitIdentifier(ident, ctx);
}
// if the ident's type is equal to the type we're looking for, and the classname of the type we're looking for is equal to the ident's string representation
// Then transform it, otherwise leave it alone
if (TypeUtils.isOfClassType(ident.getType(), originalType.getFullyQualifiedName())) {
Expand Down

0 comments on commit 3a85771

Please sign in to comment.