如何在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());

}

10-07 16:33