Pass array as value of annotation param in JavaPoet

Using JavaPoet I'm trying to annotate a class with an annotation which has an array as a parameter value i.e.

@MyCustom(param = { Bar.class, Another.class })
class Foo { 
}

I use AnnotationSpec.builder and its addMember() method:

List<TypeMirror> moduleTypes = new ArrayList<>(map.keySet());
AnnotationSpec annotationSpec = AnnotationSpec.builder(MyCustom.class)
   .addMember("param", "{ $T[] } ", moduleTypes.toArray() )
   .build();
builder.addAnnotation(annotationSpec);

Upvotes: 2

Views: 1465

Answers (2)

amurka
amurka

Reputation: 665

CodeBlock has a joining collector, and you can use that to stream this, doing something like the following (if for instance this was an enum). You can do it for any types, just the map would change.

AnnotationSpec.builder(MyCustom.class)
   .addMember(
      "param",
      "$L",
      moduleTypes.stream()
         .map(type -> CodeBlock.of("$T.$L", MyCustom.class, type))
         .collect(CodeBlock.joining(",", "{", "}")))
   .build()

Upvotes: 1

Maybe not an optimal solution but passing an array to an annotation in JavaPoet can be done in the following way:

List<TypeMirror> moduleTypes = new ArrayList<>(map.keySet());
CodeBlock.Builder codeBuilder  = CodeBlock.builder();
boolean arrayStart = true;
codeBuilder.add("{ ");
for (TypeMirror modType: moduleTypes)
    if (!arrayStart)
        codeBuilder.add(" , ");
    arrayStart = false;
    codeBuilder.add("$T.class", modType);
codeBuilder.add(" }");

AnnotationSpec annotationSpec = AnnotationSpec.builder(MyCustom.class)
    .addMember("param", codeBuilder.build() )
    .build();
builder.addAnnotation(annotationSpec);

Upvotes: 0

Related Questions