javaopenapiopenapi-generatoropenapi-generator-cli

Why does OpenAPI generate Java members/methods with underscore prefixes?


I have an OpenAPI model I'm rendering in Java. In the context (of OpenFGA) there's a model for an "object", as in, the object of a relationship. In any case it's called "object" in the model

When I render the model, I end up with member variables and methods called _object instead.

Member variables end up looking like:

    public static final String JSON_PROPERTY_OBJECT = "object";
    private String _object;

...and methods like:

    public TupleKey _object(String _object) {
        this._object = _object;
        return this;
    }

    /**
     * Get _object
     * @return _object
     **/
    @javax.annotation.Nullable
    @JsonProperty(JSON_PROPERTY_OBJECT)
    @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
    public String getObject() {
        return _object;
    }

    @JsonProperty(JSON_PROPERTY_OBJECT)
    @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
    public void setObject(String _object) {
        this._object = _object;
    }

    public TupleKey relation(String relation) {
        this.relation = relation;
        return this;
    }

Why _object? If object is not a keyword in Java, we don't need a leading underscore, right? I see the same happen with _list and _file as well.


Solution

  • It's a "reserved word" for OpenAPI generator's Java processor. (docs, code) Reserved words for Java that get processed by OpenAPI generator end up prefixing an underscore.

    As far as I can tell, the only way to opt out of this is to either patch OpenAPI or do post-processing. (Maybe someone in comments can correct me, though)


    While object is not a reserved keyword in Java as a language, it might be worth leaving as _object since it's a reserved keyword in other JVM languages.

    Those languages support bare words to get around the keyword limitation, so myModelThing.object(etc) could be valid, but it's a pain.

    While this might not be the reason it was added to OpenAPI generator's reserved words, it does mean that a client generated in Java (or derivative software) is more likely to be able to interact with other JVM languages, so unless you plan to also generate a Kotlin client and Scala client (and others?) it might be worth leaving it as-is.