Skip to content

[BUG] Java enum values are messed up #19438

Open
@mortenegelund

Description

@mortenegelund
Description

When enum values are parsed with the Java parser, they get messed up in the generated code.

For example:

  • "R2D2" becomes "R2_D2" in Java code
  • "U2F" becomes "U2_F" in Java code
openapi-generator version

Version 7.8.0

Suggested fix

This bug has been introduced with #18338

AbstractJavaCodeGen.java, line 1913:

    @Override
    public String toEnumVarName(String value, String datatype) {
        if (enumNameMapping.containsKey(value)) {
            return enumNameMapping.get(value);
        }

        if (value.length() == 0) {
            return "EMPTY";
        }

        // for symbol, e.g. $, #
        if (getSymbolName(value) != null) {
            return getSymbolName(value).toUpperCase(Locale.ROOT);
        }

        if (" ".equals(value)) {
            return "SPACE";
        }

        // number
        if ("Integer".equals(datatype) || "Long".equals(datatype) ||
                "Float".equals(datatype) || "Double".equals(datatype) || "BigDecimal".equals(datatype)) {
            String varName = "NUMBER_" + value;
            varName = varName.replaceAll("-", "MINUS_");
            varName = varName.replaceAll("\\+", "PLUS_");
            varName = varName.replaceAll("\\.", "_DOT_");
            return varName;
        }

        // string
        String var = value.replaceAll("\\W+", "_").toUpperCase(Locale.ROOT);
        if (var.matches("\\d.*")) {
            var = "_" + var;
        }
        return this.toVarName(var); <----------------Should be changed to "return var;"
    }

Related issues/PRs

#18338

Activity

jpfinne

jpfinne commented on Aug 24, 2024

@jpfinne
Contributor

Same issue as #19204

There 2 workarounds:
x-enum-varnames in the contract or enumNameMappings option

Some generators have the enumPropertyNaming option. original could solve your specific issue but you would loose the conversion to uppercase. Unfortunately no java implementation yet. There is #19277

mortenegelund

mortenegelund commented on Aug 26, 2024

@mortenegelund
Author

There are no hard enum naming conventions in Java. I suggest enum parsing should be done at an absolute minimum level just to avoid syntax errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      [BUG] Java enum values are messed up · Issue #19438 · OpenAPITools/openapi-generator