1

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);
        }
dk1337
  • 11
  • 1
  • so, basically, you don't know how to create a new annotation? – Stultuske Aug 22 '23 at 08:50
  • I can add a new annotation to a class, but I can't figure out how to an array parameter to a new annotation. – dk1337 Aug 22 '23 at 08:51
  • You mean the existing Import annotation from Spring? You 've put the code for that in your question. can't be done dynamically, though, since it's done on compile time, not runtime – Stultuske Aug 22 '23 at 08:54

0 Answers0