ReplaceAnnotation replaces with fully qualified class name #5215
-
|
I'm experimenting with OpenRewrite and now I'm trying to replace the annotation This discussion shows quite similar problems but the suggested workaround does not work in my case: #4314 This is a test that illustrates the behavior: import org.junit.jupiter.api.Test;
import org.openrewrite.java.ChangePackage;
import org.openrewrite.java.ReplaceAnnotation;
import org.openrewrite.java.ShortenFullyQualifiedTypeReferences;
import org.openrewrite.test.RewriteTest;
import static org.openrewrite.java.Assertions.java;
class JakartaAnnotationMigrationTest implements RewriteTest {
private static final String BEFORE = """
import javax.annotation.CheckForNull;
class Klasse {
private void method(@CheckForNull String aString) {
}
}
""";
private static final String AFTER = """
import jakarta.annotation.Nullable;
class Klasse {
private void method(@Nullable String aString) {
}
}
""";
// DOES NOT WORK: annotation is fully qualified name
@Test
void replaceCheckForNullByNullable_withReplaceAnnotation() {
rewriteRun(
spec -> spec.recipe(new ReplaceAnnotation("@javax.annotation.CheckForNull", "@jakarta.annotation.Nullable", null)),
java(BEFORE, AFTER)
);
}
// DOES NOT WORK: annotation is fully qualified name, even with explicite shorten recipe
@Test
void replaceCheckForNullByNullable_withReplaceAnnotationAndShortenFullyQualified() {
rewriteRun(
spec -> spec.recipes(
new ReplaceAnnotation("@javax.annotation.CheckForNull", "@jakarta.annotation.Nullable", null),
new ShortenFullyQualifiedTypeReferences()
),
java(BEFORE, AFTER)
);
}
// WORKS: annotation is replaced in shortened form with import
@Test
void replaceCheckForNullByNullable_withReplaceAnnotationAndChangePackage() {
rewriteRun(
spec -> spec.recipes(
new ReplaceAnnotation("@javax.annotation.CheckForNull", "@javax.annotation.Nullable", null),
new ChangePackage("javax.annotation", "jakarta.annotation", null)
),
java(BEFORE, AFTER)
);
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
hi! For this replacement you'll likely want to use rewrite/rewrite-core/src/main/resources/META-INF/rewrite/jspecify.yml Lines 24 to 35 in 009427e ReplaceAnnotation might work if you add a classpathResourceName argument, but that could be needlessly complicated if ChangeType already exists. |
Beta Was this translation helpful? Give feedback.
hi! For this replacement you'll likely want to use
ChangeTypeinstead. You'll find a couple more examples here:rewrite/rewrite-core/src/main/resources/META-INF/rewrite/jspecify.yml
Lines 24 to 35 in 009427e