1
註釋PARAM的值

使用JavaPoet我想要註釋的一類與具有陣列作爲參數值即通行證陣列中JavaPoet

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

我使用AnnotationSpec.builder及其addMember()方法的註釋:

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

回答

0

也許不是最佳解決方案,但將數組傳遞給在JavaPoet註釋可以通過以下方式來完成:

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);