Skip to content

[Java] Option to generate Enum values as public static final constants? #6286

@stevecookform3

Description

@stevecookform3
Description

I'd like to introduce an option to the java codegen that would generate constants rather than enums where enums are defined in swagger.

So as an example, the following model has a simple enum:

              cat_gender:
                type: string
                enum:
                  - Male
                  - Female

This currently generates the following enum:

  @JsonProperty("cat_gender")
  private CatGenderEnum catGender = null;

  /**
   * Gets or Sets catGender
   */
  public enum CatGenderEnum {
    MALE("Male"),
    
    FEMALE("Female");

    private String value;

    CatGenderEnum(String value) {
      this.value = value;
    }

    @Override
    @JsonValue
    public String toString() {
      return String.valueOf(value);
    }

    @JsonCreator
    public static CatGenderEnum fromValue(String text) {
      for (CatGenderEnum b : CatGenderEnum.values()) {
        if (String.valueOf(b.value).equals(text)) {
          return b;
        }
      }
      return null;
    }
  }

I'd like to add a codegen option that would allow you to generate simply:

  @JsonProperty("cat_gender")
  private String catGender = null;

    public static final String CATGENDER_MALE = "Male";
    public static final String CATGENDER_FEMALE = "Female";

The advantage to building this as a String is flexibility, especially when swagger is generating client code.

With the existing generation where an enum in swagger is turned into a strict Enum in java, if the server API changes to add a new value in cat_gender that is neither male nor female (e.g. MALE_NEUTERED), any existing client implementation will just see a value of null (or if #5950 is implemented, this could be possibly an UNKNOWN enum value or just throwing an Exception).

If the enum on the client is interpreted as a String, then the value can still be captured and used (for example, in log/error messages).

I couldnt find any existing option, and for the sake of backwards compatibility I'd suggest adding this as a new code generation option (initially for client java generation) using CodegenConstants.

Any thoughts/comments?

Swagger-codegen version

Latest HEAD

Command line used for generation

swagger-codegen-cli.jar -l spring

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions