-->

How to generate multiple values for a class level

2019-08-27 19:34发布

问题:

We are using JDT for generating java source code. We are stuck in generating a class where the class itself is annotated as belows:

@SomeAnnotation({Class1.class, Class2.class})

Please let me know how this can be achieved. I am using NormalAnnotation class for this but could not set the expression accordingly. Though String literals can be set but Class cannot be.

回答1:

I was able to do this using NormalAnnotation class, here is the code:

// values contains the class names.

NormalAnnotation normalAnnotation = ast.newNormalAnnotation();
Name name = ast.newName(annotationName);
normalAnnotation.setTypeName(name);
ArrayInitializer arrayInit = ast.newArrayInitializer();
for(String value : values){
  TypeLiteral tL = ast.newTypeLiteral();
  tL.setType(ast.newSimpleType(ast.newName(value)));
  arrayInit.expressions().add(tL);
}

MemberValuePair memberValuePair = ast.newMemberValuePair();
memberValuePair.setName(ast.newSimpleName("value"));
memberValuePair.setValue(arrayInit);

normalAnnotation.values().add(memberValuePair);