如何用javapoet生成Class参数?

时间:2017-06-16 07:52:22

标签: java javapoet

我需要为枚举类生成下一个java.class参数:

    public enum ServiceType {

        //....
        private final Class<?> mClass; //<<how?

        ServiceType(final Class<?> clazz) {
            this.mClass = clazz;
        }

        public Class<?> getCurrentClass() {
            return mClass;
        }
        //...
    }

我找不到 - 如何制作这个领域。

我生成此类的代码:

        File path = new File(Path.ROOT + ENUM_PATH);

        TypeSpec.Builder servicesEnumBuilder = TypeSpec.enumBuilder(ENUM_CLASS_NAME)
                .addModifiers(Modifier.PUBLIC);

        for (Map.Entry<String, String> entry: foundedServices.entrySet()) {
            servicesEnumBuilder.addEnumConstant(
                    entry.getKey().toUpperCase() + ENUM_SUFFIX,
                    TypeSpec.anonymousClassBuilder("$T", ClassName.get(entry.getValue() , entry.getKey())).build());
        }

        servicesEnumBuilder.addField(); //<< how add this field: private final Class<?> mClass;

1 个答案:

答案 0 :(得分:3)

您可以查看this answer

适用于您的情况,它将是这样的:

    TypeName wildcard = WildcardTypeName.subtypeOf(Object.class);
    TypeName classOfAny = ParameterizedTypeName.get(
            ClassName.get(Class.class), wildcard);
    FieldSpec field = FieldSpec.builder(classOfAny, "mClass")  // You may consider using a constant here
            .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
            .build();

    servicesEnumBuilder.addField(field);