Skip to content

[Java] Fix uncompilable default value for alias-as-model array/map properties (#23988) - #24008

Open
seonwooj0810 wants to merge 3 commits into
OpenAPITools:masterfrom
seonwooj0810:fix/issue-23988-alias-array-default-value
Open

seonwooj0810 wants to merge 3 commits into
OpenAPITools:masterfrom
seonwooj0810:fix/issue-23988-alias-array-default-value

Conversation

@seonwooj0810

@seonwooj0810 seonwooj0810 commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #23988

What

When generateAliasAsModel=true, a property that directly $refs an array or map alias is typed as the generated alias model (e.g. ItemArray extends ArrayList<Item>), but AbstractJavaCodegen.toDefaultValue(...) dereferenced the $ref first and produced a collection default such as new ArrayList<>(). That value is not assignable to the alias type, so the generated field does not compile:

private ItemArray itemArray = new ArrayList<>(); // ItemArray extends ArrayList<Item> -> does not compile

Fix

AbstractJavaCodegen.toDefaultValue(CodegenProperty, Schema): when the property is a $ref to an array/map alias (so it is neither an inline array nor map itself) and the referenced schema is an array/map (i.e. it is generated as an alias model), instantiate the alias model — or null when the property is nullable / containerDefaultToNull is set — instead of the inlined collection:

private ItemArray itemArray = new ItemArray();
private ItemMap itemMap = new ItemMap();

This matches the maintainer-clarified expectation in the issue thread. When generateAliasAsModel=false, the property is inlined to the collection type (cp.isArray/cp.isMap is true), so the guard does not fire and the existing new ArrayList<>() behaviour is preserved.

Test evidence

Added SpringCodegenTest#shouldUseAliasModelDefaultValueForAliasAsModelProperties_issue23988 (with spec 3_0/spring/issue_23988.yaml) which generates with generateAliasAsModel=true and asserts both the array- and map-alias fields instantiate the alias model.

  • New test passes.
  • Full AbstractJavaCodegenTest (65 tests) passes — including toDefaultValueTest and getTypeDeclarationTest, which cover the inlined-array/map default paths — so existing behaviour is unchanged.
  • Regenerated all bin/configs/java-* and bin/configs/spring* samples (197 generators): no diff, so no committed mature sample changes.

Verification done: reproduced the uncompilable output on master with the issue's spec via the CLI; confirmed the corrected output compiles (ItemArray/ItemMap have default no-arg constructors); confirmed no in-flight PR referenced #23988.

PR checklist

  • Read the contribution guidelines.
  • Ran the build and sample regeneration for the affected generators (Java/Spring); no sample changes resulted.
  • @mention technical committee — deferring to maintainers.

Summary by cubic

Fixes uncompilable defaults for properties that $ref array/map aliases when generateAliasAsModel=true. Defaults now instantiate the alias model (e.g., new ItemArray()/new ItemMap()), or null when nullable or containerDefaultToNull is set.

  • Bug Fixes
    • Updated AbstractJavaCodegen.toDefaultValue(...) to detect $ref to array/map aliases and return new <Alias>(); keeps collection defaults when generateAliasAsModel=false.
    • Added Spring tests and specs asserting alias model defaults for array and map properties, including a known limitation: explicit alias defaults fall back to an empty alias instance when generateAliasAsModel=true.
    • No sample diffs; existing tests pass.

Written for commit 86ccb52. Summary will update on new commits.

View guided diff

…operties

When generateAliasAsModel is enabled, a property that $refs an array/map
alias is typed as the generated alias model (e.g. "ItemArray extends
ArrayList<Item>"), but toDefaultValue dereferenced the $ref and produced a
collection default such as "new ArrayList<>()", which is not assignable to
the alias type and does not compile. Use the alias model's own default
("new ItemArray()") instead.

Fixes OpenAPITools#23988

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: seonwoo_jung <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 3 files

Re-trigger cubic

@seonwooj0810

Copy link
Copy Markdown
Contributor Author

Flagging this one for review whenever there's bandwidth — happy to regenerate samples again if main has moved since.

@seonwooj0810

Copy link
Copy Markdown
Contributor Author

Merged current master in 95f32e4 to resolve the conflict in AbstractJavaCodegen.toDefaultValue. The upstream explicit/complex-default handling stays first, followed by the alias-model fallback. GitHub now reports no merge conflict.

Verified on JDK 21:

  • SpringCodegenTest and AbstractJavaCodegenTest: 455 tests passed.
  • CLI package build passed.
  • Regenerated all bin/configs/java-* and bin/configs/spring* samples: 210 generators passed, no sample changes.

@Sekator778 Sekator778 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced #23988 on master, and with this Spring and okhttp-gson compile. LGTM.

@seonwooj0810

Copy link
Copy Markdown
Contributor Author

Thanks for reproducing and reviewing, @Sekator778!

@AndreyVMarkelov

Copy link
Copy Markdown
Contributor

I tested an array alias with default: [hello]. With generateAliasAsModel=false, the generated field is initialized with ["hello"]; with generateAliasAsModel=true, it is initialized with an empty ItemArray.

Is this difference expected, or should explicit alias defaults be handled separately? It may be useful to add a test documenting the intended behavior.

@seonwooj0810

Copy link
Copy Markdown
Contributor Author

Not intended, it is a limitation of this fix: the generated alias model only has a no-arg constructor, so with generateAliasAsModel=true the [hello] values can't be expressed in a field initializer and it falls back to new ItemArray() (on master this case fails model generation with "Codegen Property must be array/set/map"). I added a test for both modes in 86ccb52; keeping the values would need a collection constructor on the alias model templates, which I'd rather do as a follow-up unless you want it in this PR.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 4 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java">

<violation number="1" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java:1458">
P2: This `$ref` branch also matches object models that have `properties` plus `additionalProperties`, because `isMapSchema` is true for them. Those are real model classes, not aliases, so they now get `new Foo()` where the existing map branch returned `null`. Exclude schemas with properties here so only alias-style maps take this path.</violation>
</file>

<file name="modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java">

<violation number="1" location="modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java:7176">
P2: This test asserts that the spec default `[hello]` on `ItemArray` is silently dropped when `generateAliasAsModel=true`. Pinning that output in a test means any future fix for the default will fail this test. Either leave the assertion out, or assert that the limitation is surfaced (for example, a warning) if the codegen emits one.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

// "new ArrayList<>()", which is not assignable to the alias type and does not compile.
// Use the alias model's own default instead.
// See https://github.com/OpenAPITools/openapi-generator/issues/23988
if (originalSchema.get$ref() != null && !cp.isArray && !cp.isMap) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This $ref branch also matches object models that have properties plus additionalProperties, because isMapSchema is true for them. Those are real model classes, not aliases, so they now get new Foo() where the existing map branch returned null. Exclude schemas with properties here so only alias-style maps take this path.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java, line 1458:

<comment>This `$ref` branch also matches object models that have `properties` plus `additionalProperties`, because `isMapSchema` is true for them. Those are real model classes, not aliases, so they now get `new Foo()` where the existing map branch returned `null`. Exclude schemas with properties here so only alias-style maps take this path.</comment>

<file context>
@@ -1449,6 +1449,21 @@ public String toDefaultValue(CodegenProperty cp, Schema schema) {
+        // "new ArrayList<>()", which is not assignable to the alias type and does not compile.
+        // Use the alias model's own default instead.
+        // See https://github.com/OpenAPITools/openapi-generator/issues/23988
+        if (originalSchema.get$ref() != null && !cp.isArray && !cp.isMap) {
+            if (ModelUtils.isArraySchema(resolvedSchema)
+                    || (ModelUtils.isMapSchema(resolvedSchema) && !ModelUtils.isComposedSchema(resolvedSchema))) {
</file context>

// generateAliasAsModel=true: known limitation. The generated alias model only has a no-arg
// constructor, so the explicit default values cannot be expressed in a field initializer and
// the field falls back to an empty alias instance (previously model generation failed here).
JavaFileAssert.assertThat(generateIssue23988DefaultModel(true).get("MyObject.java"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This test asserts that the spec default [hello] on ItemArray is silently dropped when generateAliasAsModel=true. Pinning that output in a test means any future fix for the default will fail this test. Either leave the assertion out, or assert that the limitation is surfaced (for example, a warning) if the codegen emits one.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java, line 7176:

<comment>This test asserts that the spec default `[hello]` on `ItemArray` is silently dropped when `generateAliasAsModel=true`. Pinning that output in a test means any future fix for the default will fail this test. Either leave the assertion out, or assert that the limitation is surfaced (for example, a warning) if the codegen emits one.</comment>

<file context>
@@ -7131,6 +7131,77 @@ public void shouldAddNullableImportForArrayTypeModels() throws IOException {
+        // generateAliasAsModel=true: known limitation. The generated alias model only has a no-arg
+        // constructor, so the explicit default values cannot be expressed in a field initializer and
+        // the field falls back to an empty alias instance (previously model generation failed here).
+        JavaFileAssert.assertThat(generateIssue23988DefaultModel(true).get("MyObject.java"))
+                .fileContains("private ItemArray itemArray = new ItemArray();");
+    }
</file context>

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG][JAVA][MAVEN] Array aliases generate uncompilable Java code with generateAliasAsModel=true

3 participants