Skip to content

[java][native] support useOneOfInterfaces and useDeductionForOneOfInterfaces - #25813

Open
thorstenhirsch wants to merge 1 commit into
OpenAPITools:masterfrom
thorstenhirsch:java-native-oneof-interfaces
Open

thorstenhirsch wants to merge 1 commit into
OpenAPITools:masterfrom
thorstenhirsch:java-native-oneof-interfaces

Conversation

@thorstenhirsch

@thorstenhirsch thorstenhirsch commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Title

[java][native] support useOneOfInterfaces / useDeductionForOneOfInterfaces

Description

Related to #25727 and #25728.

With library=native, useOneOfInterfaces=true currently produces code that does not compile. native/model.mustache ignores x-is-one-of-interface and always renders the oneof_model wrapper class (extends AbstractOpenApiSchema), but DefaultCodegen still makes the members implement the oneOf type:

[ERROR] .../model/ServiceAuthor.java:[38,39] interface expected here

As a consequence useDeductionForOneOfInterfaces cannot be used with native either, although it is the way to resolve a oneOf without discriminator by the set of properties (as pointed out by @jpfinne in #25727).

This PR makes native honour the option, the same way okhttp already does:

  • libraries/native/model.mustache and model_doc.mustache dispatch to the shared oneof_interface / pojo_doc templates for x-is-one-of-interface models. Without useOneOfInterfaces nothing changes (wrapper class with getActualInstance()).
  • The generated api classes call toUrlQueryString(...) on deepObject / exploded query parameters. To keep that compiling for a oneOf type, the interface declares toUrlQueryString(String prefix) (plus a default no-arg variant, because enums only implement the prefix variant). This is guarded by supportUrlQuery, like in the pojo. To avoid copying the whole template, the shared oneof_interface.mustache got a hook partial oneof_interface_members, which is empty for every library except native.
  • Works with Jackson 2 and Jackson 3 (the annotations stay in com.fasterxml.jackson.annotation).

Example (spec from #25727, useOneOfInterfaces=true,useDeductionForOneOfInterfaces=true):

@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
@JsonSubTypes({
    @JsonSubTypes.Type(value = ServiceAuthor.class),
    @JsonSubTypes.Type(value = UserAuthor.class)
})
public interface Author { ... }

public class ServiceAuthor implements Author { ... }

{"subject":"Jane"} → ServiceAuthor, {"id":"u-1","domainId":"acme"} → UserAuthor, {"unknown":1} is rejected.

Please note: Jackson's deduction only looks at which properties are present, not at required. {"id":"u-1"} is therefore resolved to UserAuthor (it is the only variant that has an id), it is not rejected. Combine it with generateJsonCreator from #25728 if missing required properties must be rejected, too.

useSealedOneOfInterfaces is still not supported for native (the native pojos are not final); this PR does not change that.

Tests

  • JavaClientCodegenTest: discriminator interface, deduction interface (Jackson 2 and 3), supportUrlQuery=false, and a regression test that native without useOneOfInterfaces still generates the wrapper class. All generated sources are compiled by validateJavaSourceFiles.
  • New sample samples/client/others/java/native-oneof-interface (added to the JDK11 sample workflow) with deserialization tests in AuthorTest.
  • All other Java samples are unchanged by the regeneration.

PR checklist

  • Read the contribution guidelines.
  • Run the following to build the project and update samples:
    ./mvnw clean package || exit
    ./bin/generate-samples.sh ./bin/configs/*.yaml || exit
    ./bin/utils/export_docs_generators.sh || exit
    
    (For Windows users, please run the script in WSL)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@bbdouglas (2017/07) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) @karismann (2019/03) @Zomzog (2019/04) @lwlee2608 (2019/10) @martin-mfg (2023/08) @KannaKim (2026/07) @AndreyVMarkelov (2026/11)

🤖 Generated with Claude Code


Summary by cubic

Makes the native Java library honor useOneOfInterfaces=true, fixing generated code that previously failed to compile, and enables useDeductionForOneOfInterfaces for oneOf schemas without a discriminator.

Previously the native templates always rendered the oneOf wrapper class while members still implemented the oneOf interface type, producing interface expected here errors. The templates now dispatch to the shared oneof_interface template like the okhttp library does.

Details

  • The oneOf interface declares toUrlQueryString() (prefix and default no-arg variants) via a new oneof_interface_members hook, empty for all other libraries and guarded by supportUrlQuery.
  • Works with both Jackson 2 and Jackson 3.
  • Adds tests and a new native-oneof-interface sample with deserialization tests, registered in the JDK11 sample workflow.
  • useSealedOneOfInterfaces remains unsupported for native.
  • Jackson's deduction matches on property presence only, not required; combine with generateJsonCreator ([java][native] add generateJsonCreator to distinguish between oneOf types w/o discriminator #25728) to reject payloads with missing required properties.

Written for commit 3458e02. Summary will update on new commits.

View guided diff

…erfaces

The native library ignored useOneOfInterfaces in model.mustache and always
rendered the oneOf wrapper class, while DefaultCodegen still made the member
models implement the oneOf type. The generated code therefore failed to
compile ("interface expected here"), which also made
useDeductionForOneOfInterfaces unusable for oneOf schemas without a
discriminator.

- native/model.mustache and model_doc.mustache dispatch to the shared
  oneof_interface / pojo_doc templates for x-is-one-of-interface models, like
  the okhttp library does.
- The generated api classes call toUrlQueryString on deepObject and exploded
  query parameters, so the interface declares it (guarded by supportUrlQuery)
  through a new oneof_interface_members hook partial that is empty for all
  other libraries.
- Add unit tests, a native-oneof-interface sample with deserialization tests
  and wire it into the JDK11 sample workflow.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@thorstenhirsch
thorstenhirsch marked this pull request as ready for review November 25, 2026 03:27
@thorstenhirsch

Copy link
Copy Markdown
Contributor Author

@jpfinne Here's the new PR that adds/fixes support for useOneOfInterfaces and useDeductionForOneOfInterfaces to the native library. It does not contain or require the generateJsonCreator patch from #25728.

@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.

8 issues found across 52 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="samples/client/others/java/native-oneof-interface/src/test/java/org/openapitools/client/model/AuthorTest.java">

<violation number="1" location="samples/client/others/java/native-oneof-interface/src/test/java/org/openapitools/client/model/AuthorTest.java:42">
P2: These regression tests never execute in the Maven sample: `pom.xml` declares `junit-jupiter-api` but no `junit-jupiter-engine`, while CI runs `mvn clean package`. Add the Jupiter engine to the Maven test dependencies so this test can fail the build when deserialization breaks.</violation>
</file>

<file name="modules/openapi-generator/src/main/resources/Java/libraries/native/model.mustache">

<violation number="1" location="modules/openapi-generator/src/main/resources/Java/libraries/native/model.mustache:67">
P2: With `useSealedOneOfInterfaces=true`, native now emits `sealed interface ... permits ...` through the new `oneof_interface` branch. The PR says sealed is unsupported for native, and the code has no guard for it. Add a native guard that rejects or ignores the option, or confirm the generated Java 11 build compiles.</violation>
</file>

<file name="samples/client/others/java/native-oneof-interface/docs/DefaultApi.md">

<violation number="1" location="samples/client/others/java/native-oneof-interface/docs/DefaultApi.md:27">
P2: The API documentation examples import a nonexistent plural `models` package. Change each example to `org.openapitools.client.model.*` so the snippets compile against this client.</violation>

<violation number="2" location="samples/client/others/java/native-oneof-interface/docs/DefaultApi.md:69">
P3: The POST endpoint documentation says no `Accept` header exists, but the generated request sends `Accept: application/json`. List `application/json` for both create operations to keep the documentation consistent with the client and specification.</violation>
</file>

<file name=".github/workflows/samples-java-client-jdk11.yaml">

<violation number="1" location=".github/workflows/samples-java-client-jdk11.yaml:115">
P2: This matrix entry never exercises the sample's Gradle build because the workflow checks for `./gradlew` at repository root. Gate the step with `hashFiles(format('{0}/gradlew', matrix.sample))` instead.</violation>
</file>

<file name="samples/client/others/java/native-oneof-interface/README.md">

<violation number="1" location="samples/client/others/java/native-oneof-interface/README.md:89">
P2: The Getting Started example cannot compile because `Author` is generated as an interface. Instantiate a concrete variant such as `new ServiceAuthor().subject("Jane")`, and update the repeated API examples as well.</violation>
</file>

<file name="samples/client/others/java/native-oneof-interface/src/main/java/org/openapitools/client/ServerConfiguration.java">

<violation number="1" location="samples/client/others/java/native-oneof-interface/src/main/java/org/openapitools/client/ServerConfiguration.java:55">
P2: `ServerConfiguration.URL` dereferences `enumValues` even though `ServerVariable` permits it to be null. Guard the collection before checking its size so variables without enum constraints can be overridden.</violation>
</file>

<file name="samples/client/others/java/native-oneof-interface/src/main/java/org/openapitools/client/api/DefaultApi.java">

<violation number="1" location="samples/client/others/java/native-oneof-interface/src/main/java/org/openapitools/client/api/DefaultApi.java:338">
P2: `getAuthor` decodes JSON with the platform default charset, corrupting non-ASCII responses on non-UTF-8 JVMs. Decode the bytes as UTF-8 before deserialization.</violation>
</file>

Tip: Get a Slack DM when cubic finishes reviewing your PRs. Connect Slack

View guided diff | Re-trigger cubic

private final com.fasterxml.jackson.databind.ObjectMapper mapper = new org.openapitools.client.JSON().getMapper();

@Test
void deducesServiceAuthorFromSubject() throws Exception {

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: These regression tests never execute in the Maven sample: pom.xml declares junit-jupiter-api but no junit-jupiter-engine, while CI runs mvn clean package. Add the Jupiter engine to the Maven test dependencies so this test can fail the build when deserialization breaks.

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 samples/client/others/java/native-oneof-interface/src/test/java/org/openapitools/client/model/AuthorTest.java, line 42:

<comment>These regression tests never execute in the Maven sample: `pom.xml` declares `junit-jupiter-api` but no `junit-jupiter-engine`, while CI runs `mvn clean package`. Add the Jupiter engine to the Maven test dependencies so this test can fail the build when deserialization breaks.</comment>

<file context>
@@ -0,0 +1,70 @@
+    private final com.fasterxml.jackson.databind.ObjectMapper mapper = new org.openapitools.client.JSON().getMapper();
+
+    @Test
+    void deducesServiceAuthorFromSubject() throws Exception {
+        Author author = mapper.readValue("{\"subject\":\"Jane\"}", Author.class);
+
</file context>

{{/vendorExtensions.x-is-one-of-interface}}

{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>oneof_model}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>anyof_model}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>pojo}}{{/anyOf}}{{/oneOf}}{{/isEnum}}
{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#vendorExtensions.x-is-one-of-interface}}{{>oneof_interface}}{{/vendorExtensions.x-is-one-of-interface}}{{^vendorExtensions.x-is-one-of-interface}}{{#oneOf}}{{#-first}}{{>oneof_model}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>anyof_model}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>pojo}}{{/anyOf}}{{/oneOf}}{{/vendorExtensions.x-is-one-of-interface}}{{/isEnum}}

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: With useSealedOneOfInterfaces=true, native now emits sealed interface ... permits ... through the new oneof_interface branch. The PR says sealed is unsupported for native, and the code has no guard for it. Add a native guard that rejects or ignores the option, or confirm the generated Java 11 build compiles.

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/resources/Java/libraries/native/model.mustache, line 67:

<comment>With `useSealedOneOfInterfaces=true`, native now emits `sealed interface ... permits ...` through the new `oneof_interface` branch. The PR says sealed is unsupported for native, and the code has no guard for it. Add a native guard that rejects or ignores the option, or confirm the generated Java 11 build compiles.</comment>

<file context>
@@ -56,12 +56,14 @@ import org.hibernate.validator.constraints.*;
+{{/vendorExtensions.x-is-one-of-interface}}
 
-{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>oneof_model}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>anyof_model}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>pojo}}{{/anyOf}}{{/oneOf}}{{/isEnum}}
+{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#vendorExtensions.x-is-one-of-interface}}{{>oneof_interface}}{{/vendorExtensions.x-is-one-of-interface}}{{^vendorExtensions.x-is-one-of-interface}}{{#oneOf}}{{#-first}}{{>oneof_model}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>anyof_model}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>pojo}}{{/anyOf}}{{/oneOf}}{{/vendorExtensions.x-is-one-of-interface}}{{/isEnum}}
 {{/model}}
 {{/models}}
</file context>

import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.models.*;

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: The API documentation examples import a nonexistent plural models package. Change each example to org.openapitools.client.model.* so the snippets compile against this client.

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 samples/client/others/java/native-oneof-interface/docs/DefaultApi.md, line 27:

<comment>The API documentation examples import a nonexistent plural `models` package. Change each example to `org.openapitools.client.model.*` so the snippets compile against this client.</comment>

<file context>
@@ -0,0 +1,262 @@
+import org.openapitools.client.ApiClient;
+import org.openapitools.client.ApiException;
+import org.openapitools.client.Configuration;
+import org.openapitools.client.models.*;
+import org.openapitools.client.api.DefaultApi;
+
</file context>

- samples/client/others/java/jersey2-oneOf-duplicates/
- samples/client/others/java/jersey2-oneOf-Mixed/
- samples/client/others/java/native-oneOf-array/
- samples/client/others/java/native-oneof-interface/

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 matrix entry never exercises the sample's Gradle build because the workflow checks for ./gradlew at repository root. Gate the step with hashFiles(format('{0}/gradlew', matrix.sample)) instead.

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 .github/workflows/samples-java-client-jdk11.yaml, line 115:

<comment>This matrix entry never exercises the sample's Gradle build because the workflow checks for `./gradlew` at repository root. Gate the step with `hashFiles(format('{0}/gradlew', matrix.sample))` instead.</comment>

<file context>
@@ -110,6 +112,7 @@ jobs:
           - samples/client/others/java/jersey2-oneOf-duplicates/
           - samples/client/others/java/jersey2-oneOf-Mixed/
           - samples/client/others/java/native-oneOf-array/
+          - samples/client/others/java/native-oneof-interface/
           - samples/client/others/java/resttemplate-list-schema-validation/
           - samples/client/petstore/java/okhttp-gson-3.1-duplicated-operationid/
</file context>

// Configure clients using the `defaultClient` object, such as
// overriding the host and port, timeout, etc.
DefaultApi apiInstance = new DefaultApi(defaultClient);
Author author = new Author(); // Author |

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: The Getting Started example cannot compile because Author is generated as an interface. Instantiate a concrete variant such as new ServiceAuthor().subject("Jane"), and update the repeated API examples as well.

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 samples/client/others/java/native-oneof-interface/README.md, line 89:

<comment>The Getting Started example cannot compile because `Author` is generated as an interface. Instantiate a concrete variant such as `new ServiceAuthor().subject("Jane")`, and update the repeated API examples as well.</comment>

<file context>
@@ -0,0 +1,137 @@
+        // Configure clients using the `defaultClient` object, such as
+        // overriding the host and port, timeout, etc.
+        DefaultApi apiInstance = new DefaultApi(defaultClient);
+        Author author = new Author(); // Author | 
+        try {
+            apiInstance.createAuthor(author);
</file context>


if (variables != null && variables.containsKey(name)) {
value = variables.get(name);
if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) {

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: ServerConfiguration.URL dereferences enumValues even though ServerVariable permits it to be null. Guard the collection before checking its size so variables without enum constraints can be overridden.

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 samples/client/others/java/native-oneof-interface/src/main/java/org/openapitools/client/ServerConfiguration.java, line 55:

<comment>`ServerConfiguration.URL` dereferences `enumValues` even though `ServerVariable` permits it to be null. Guard the collection before checking its size so variables without enum constraints can be overridden.</comment>

<file context>
@@ -0,0 +1,72 @@
+
+            if (variables != null && variables.containsKey(name)) {
+                value = variables.get(name);
+                if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) {
+                    throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + ".");
+                }
</file context>
Suggested change
if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) {
if (serverVariable.enumValues != null && serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) {




String responseBody = new String(localVarResponseBody.readAllBytes());

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: getAuthor decodes JSON with the platform default charset, corrupting non-ASCII responses on non-UTF-8 JVMs. Decode the bytes as UTF-8 before deserialization.

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 samples/client/others/java/native-oneof-interface/src/main/java/org/openapitools/client/api/DefaultApi.java, line 338:

<comment>`getAuthor` decodes JSON with the platform default charset, corrupting non-ASCII responses on non-UTF-8 JVMs. Decode the bytes as UTF-8 before deserialization.</comment>

<file context>
@@ -0,0 +1,383 @@
+
+        
+        
+        String responseBody = new String(localVarResponseBody.readAllBytes());
+        Author responseValue = responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference<Author>() {});
+        
</file context>

### HTTP request headers

- **Content-Type**: application/json
- **Accept**: Not defined

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.

P3: The POST endpoint documentation says no Accept header exists, but the generated request sends Accept: application/json. List application/json for both create operations to keep the documentation consistent with the client and specification.

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 samples/client/others/java/native-oneof-interface/docs/DefaultApi.md, line 69:

<comment>The POST endpoint documentation says no `Accept` header exists, but the generated request sends `Accept: application/json`. List `application/json` for both create operations to keep the documentation consistent with the client and specification.</comment>

<file context>
@@ -0,0 +1,262 @@
+### HTTP request headers
+
+- **Content-Type**: application/json
+- **Accept**: Not defined
+
+### HTTP response details
</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.

1 participant