2017-06-16 71 views
0

我需要生成枚舉類旁邊的java.class參數:如何用javapoet生成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; 

回答

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);