如何在 Javapoet 中生成 @StringDef 枚举?注释仅可用于方法或类型构建器,而 StringDefs 是三个注释语句,没有这两个语句。
问问题
185 次
1 回答
1
使用 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());
}
于 2017-03-05T06:33:04.020 回答