如何使用JavaPoet构造具有自定义类型的枚举
是否可以使用JavaPoet生成以下枚举类如何使用JavaPoet构造具有自定义类型的枚举,java,javapoet,Java,Javapoet,是否可以使用JavaPoet生成以下枚举类 public enum EnumName { import com.sth.sth.SomeClass1; import com.sth.sth.SomeClass2; ITEM1(new CustomType<SomeClass1>("string1", "string 2", SomeClass1.class)), ITEM2(new CustomType<SomeClass2>("string1", "
public enum EnumName {
import com.sth.sth.SomeClass1;
import com.sth.sth.SomeClass2;
ITEM1(new CustomType<SomeClass1>("string1", "string 2", SomeClass1.class)),
ITEM2(new CustomType<SomeClass2>("string1", "string 2", SomeClass2.class));
EnumName(CustomType customType) {
this.customType = customType;
}
private final CustomType customType;
public CustomType getCustomType() {
return customType;
}
}
我创造了这个
public enum EnumName {
ITEM1("ITEM1"){
@Override
public CustomType getCustomType(){
return new CustomType<SomeClass1>("string1", "string 2", SomeClass1.class));
}
},
ITEM2("ITEM2"){
@Override
public CustomType getCustomType(){
return new CustomType<SomeClass2>("string1", "string 2", SomeClass2.class));
}
};
EnumName(customTypeName customTypeName) {
this.customTypeName = customTypeName;
}
private final String customTypeName;
public String getCustomTypeName() {
return customTypeName;
}
这部分还可以,但我不知道如何为这些类生成导入
我喜欢第一种选择
ITEM1(new CustomType<SomeClass1>("string1", "string 2", SomeClass1.class))
ITEM1(新的自定义类型(“string1”、“string2”、SomeClass1.class))
但如果不能做到,有人能建议如何为第二个示例生成导入,并调整周期吗
非常感谢您的建议。如果有人对未来感兴趣,请找到解决方案
String fullyQualifiedClassName = getClassName();
if (fullyQualifiedClassName == null) {
fullyQualifiedClassName = "Object"; //important if class was not found we need set to object -> otherwise there will not be imports for some reason
}
TypeName typeName = ClassName.bestGuess(fullyQualifiedClassName);
for (Model model : models) {
typeSpecBuilder.addEnumConstant(prepareName(model), TypeSpec.anonymousClassBuilder("new CustomType<$T>($S, $S, $T.class)", typeName, string1, string2, typeName));
}
String fullyQualifiedClassName=getClassName();
if(fullyQualifiedClassName==null){
fullyQualifiedClassName=“Object”//如果找不到类,则需要设置为Object->否则由于某种原因将不会导入
}
TypeName TypeName=ClassName.bestGuess(fullyQualifiedClassName);
用于(模型:模型){
typeSpecBuilder.addEnumConstant(prepareName(模型),TypeSpec.anonymousClassBuilder(“新自定义类型($S,$S,$T.class)”,typeName,string1,string2,typeName));
}
ITEM1(new CustomType<SomeClass1>("string1", "string 2", SomeClass1.class))
String fullyQualifiedClassName = getClassName();
if (fullyQualifiedClassName == null) {
fullyQualifiedClassName = "Object"; //important if class was not found we need set to object -> otherwise there will not be imports for some reason
}
TypeName typeName = ClassName.bestGuess(fullyQualifiedClassName);
for (Model model : models) {
typeSpecBuilder.addEnumConstant(prepareName(model), TypeSpec.anonymousClassBuilder("new CustomType<$T>($S, $S, $T.class)", typeName, string1, string2, typeName));
}