I'm trying to dynamically add arguments to an array parameter an in annotation. I'm writing my own recipe.
Expected result:
@Import({
TestConfiguration.class,
XyzConfiguration.class,
AbcConfiguration.class,
...
})
I can add new annotation to a class, but I can't figure it out how to an array parameter to @Import
annotation.
private static class ImportVisitor extends JavaIsoVisitor<ExecutionContext> {
private static final String IMPORT_ANNOTATION = "Import";
private static final String SPRING_BOOT_APPLICATION_ANNOTATION = "SpringBootApplication";
@Override
public @NonNull ClassDeclaration visitClassDeclaration(
@NonNull ClassDeclaration classDecl,
@NonNull ExecutionContext executionContext
) {
boolean isApplication = classDecl.getSimpleName().contains("Application");
boolean isImport = classDecl.getAllAnnotations()
.stream()
.anyMatch(annotation -> IMPORT_ANNOTATION.equals(annotation.getSimpleName()));
if (isApplication && !isImport) {
List<Annotation> annotations = classDecl.getAllAnnotations();
Annotation importAnnotation = createAnnotation(IMPORT_ANNOTATION);
annotations.add(importAnnotation);
annotations.add(createAnnotation(SPRING_BOOT_APPLICATION_ANNOTATION).withPrefix(Space.format("\n")));
classDecl = classDecl.withPrefix(Space.format("\n"))
.withLeadingAnnotations(annotations)
maybeAddImport("org.springframework.boot.autoconfigure.SpringBootApplication", false);
maybeAddImport("org.springframework.context.annotation.Import", false);
}
return classDecl;
}
public static J.Annotation createAnnotation(String annotation) {
return new J.Annotation(UUID.randomUUID(),
Space.EMPTY,
Markers.EMPTY,
TypeTree.build(annotation),
null);
}