Is there a way to add a dynamic list of EnumConstants - I would expect to see addEnumConstants()
.
There seems to be no parallel to addFields()
or addMethods()
?
There are indeed no methods to add a list of enum constants. Quoting from the documentation:
Use
enumBuilder
to create the enum type, andaddEnumConstant()
for each value:
In this case, you will need to loop over all of your enum values and add them one by one by calling addEnumConstant()
on the builder instance.
Sample code that adds all the enum frol the List<String> myEnumList
:
TypeSpec.Builder builder = TypeSpec.enumBuilder("Roshambo").addModifiers(Modifier.PUBLIC);
for (String str : myEnumList) {
builder.addEnumConstant(str);
}
TypeSpec typeSpec = builder.build();
Please see JavaPoet for adding enum constants. You can start creating a TypeSpec.Builder and call .addEnumConstant in a loop from a list of values.
However, if you do not have your enum constants list prior to generating the enum type, you cannot generate them dynamically. Enums constants have to be a constant list in an enum class. An alternative is to generate a singleton class with a dynamic list of valid values and a .get static function that replaces an enum's .valueOf function.