Search code examples
javajavapoet

JavaPoet adding a list of enum constants


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()?


Solution

  • There are indeed no methods to add a list of enum constants. Quoting from the documentation:

    Use enumBuilder to create the enum type, and addEnumConstant() 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();