如何在javapoet中生成@stringdef枚举?注释仅适用于方法或类型的构建器,而StringDefs则是三个没有两个注释语句。
使用javapoet 1.8.0 使用这样的代码:
private void createEnumStringDef(TypeSpec.Builder beanBuilder, String enumName, List<String> enumValues) {
String defValues = "{";
for (String defVal :enumValues) {
defValues += enumName +"." +defVal.toUpperCase() +",";
}
defValues = Utils.removeLastChar(defValues) + "}";
TypeSpec.Builder stringDef = TypeSpec.annotationBuilder(enumName)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(AnnotationSpec.builder(ClassName.get("android.support.annotation", "StringDef")).addMember("value", defValues).build())
.addAnnotation(AnnotationSpec.builder(ClassName.get("java.lang.annotation", "Retention")).addMember("value", "$T.SOURCE", ClassName.get("java.lang.annotation", "RetentionPolicy")).build());
for (String defVal : field.enumValues) {
stringDef.addField(FieldSpec.builder(String.class, defVal.toUpperCase())
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer("$S", defVal)
.build());
}
beanBuilder.addType(stringDef.build());
}