Skip to content

Commit

Permalink
ShortenFullyQualifiedTypeReferences: Preserve prefix of annotation
Browse files Browse the repository at this point in the history
Fixes: #3870
  • Loading branch information
knutwannheden committed Jan 3, 2024
1 parent 384a511 commit 77ab3fb
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Issue;
import org.openrewrite.java.service.ImportService;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
Expand Down Expand Up @@ -568,4 +569,39 @@ class Test {
)
);
}

@Issue("https://github.com/openrewrite/rewrite/issues/3870")
@Test
void typeFullyQualifiedAnnotatedField() {
rewriteRun(
java(
"""
import java.sql.DatabaseMetaData;
import java.util.List;
import java.lang.annotation.*;
class TypeAnnotationTest {
protected java.sql.@A DatabaseMetaData metadata;
@Target({ElementType.FIELD, ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
private @interface A {
}
}
""",
"""
import java.sql.DatabaseMetaData;
import java.util.List;
import java.lang.annotation.*;
class TypeAnnotationTest {
protected @A DatabaseMetaData metadata;
@Target({ElementType.FIELD, ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
private @interface A {
}
}
"""
)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -641,9 +641,9 @@ public J visitForEachLoop(ForEachLoop forEachLoop, PrintOutputCapture<P> p) {

@Override
public J visitIdentifier(Identifier ident, PrintOutputCapture<P> p) {
visitSpace(Space.EMPTY, Space.Location.ANNOTATIONS, p);
visit(ident.getAnnotations(), p);
beforeSyntax(ident, Space.Location.IDENTIFIER_PREFIX, p);
visitSpace(Space.EMPTY, Space.Location.ANNOTATIONS, p);
p.append(ident.getSimpleName());
afterSyntax(ident, p);
return ident;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ public J visitFieldAccess(J.FieldAccess fieldAccess, ExecutionContext ctx) {
String simpleName = fieldAccess.getSimpleName();
JavaType usedType = usedTypes.get(simpleName);
if (type == usedType || signatureBuilder.signature(type).equals(signatureBuilder.signature(usedType))) {
return fieldAccess.getName().withPrefix(fieldAccess.getPrefix());
return !fieldAccess.getPrefix().isEmpty() ? fieldAccess.getName().withPrefix(fieldAccess.getPrefix()) : fieldAccess.getName();
} else if (!usedTypes.containsKey(simpleName)) {
String fullyQualifiedName = ((JavaType.FullyQualified) type).getFullyQualifiedName();
if (!fullyQualifiedName.startsWith("java.lang.")) {
Expand Down

0 comments on commit 77ab3fb

Please sign in to comment.