You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@fory.apache.org by ch...@apache.org on 2026/08/23 14:29:34 UTC
(fory) branch main updated: feat(java): add sealed interface json subtypes support (#3968)
This is an automated email from the ASF dual-hosted git repository.
chaokunyang pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/fory.git
The following commit(s) were added to refs/heads/main by this push:
new fd390b704 feat(java): add sealed interface json subtypes support (#3968)
fd390b704 is described below
commit fd390b704562bd72260dc58e0ed794d70cef1d80
Author: Shawn Yang <sh...@gmail.com>
AuthorDate: Sun Aug 23 22:29:30 2026 +0800
feat(java): add sealed interface json subtypes support (#3968)
## Why?
## What does this PR do?
add sealed interface json subtypes support
## Related issues
Closes #3964
## AI Contribution Checklist
- [ ] Substantial AI assistance was used in this PR: `yes` / `no`
- [ ] If `yes`, I included a completed [AI Contribution
Checklist](https://github.com/apache/fory/blob/main/AI_POLICY.md#9-contributor-checklist-for-ai-assisted-prs)
in this PR description and the required `AI Usage Disclosure`.
- [ ] If `yes`, my PR description includes the required `ai_review`
summary and screenshot evidence or equivalent persisted links of the
final clean AI review results from both fresh reviewers described in
`AI_POLICY.md`, the Fory-guided reviewer and the independent general
reviewer, on the current PR diff or current HEAD after the latest code
changes.
## Does this PR introduce any user-facing change?
- [ ] Does this PR introduce any public API change?
- [ ] Does this PR introduce any binary protocol compatibility change?
## Benchmark
---
AGENTS.md | 15 +-
ci/tasks/kotlin.py | 4 +
docs/json/android.md | 103 ++++---
docs/json/annotations.md | 88 +++---
docs/json/getting-started.md | 9 +-
docs/json/graalvm.md | 18 +-
docs/json/kotlin.md | 41 +--
docs/json/scala.md | 29 +-
docs/json/security.md | 12 +-
docs/security/deserialization.md | 15 +
integration_tests/android_tests/build.gradle | 23 +-
integration_tests/android_tests/proguard-rules.pro | 2 +
.../fory/android/ForyAndroidInstrumentedTest.java | 10 +
.../apache/fory/android/AndroidJsonScenarios.java | 12 +-
.../apache/fory/android/GeneratedJsonModel.java | 9 +-
.../apache/fory/android/GeneratedMixinShape.java | 34 +--
.../android/GeneratedMixinShapeAnnotations.java | 31 +--
.../java/org/apache/fory/android/KspJavaShape.java | 34 +--
.../fory/android/AndroidKotlinJsonScenarios.kt | 15 +
.../org/apache/fory/graalvm/ForyJsonExample.java | 33 ++-
.../kotlin/json/corpus/PlatformModels.kt | 49 +++-
.../integration/kotlin/json/corpus/cases/root.json | 2 +-
.../kotlin/json/corpus/KspRetentionResourceTest.kt | 15 +
java/fory-annotation-processor/pom.xml | 123 +++++++++
.../annotation/processing/ForyStructProcessor.java | 5 +
.../annotation/processing/GeneratedTypeNames.java | 9 +
.../annotation/processing/JsonTypeProcessor.java | 290 +++++++++++++++++++-
.../annotation/processing/SealedTypeSupport.java | 36 +--
.../annotation/processing/SealedTypeSupport.java | 45 +++
.../processing/JsonTypeProcessorTest.java | 152 +++++++++++
java/fory-json/pom.xml | 35 +++
.../java/org/apache/fory/json/ForyJsonBuilder.java | 4 +
.../java/org/apache/fory/json/JsonTypeChecker.java | 5 +
.../apache/fory/json/annotation/JsonSubTypes.java | 17 +-
.../apache/fory/json/codec/ClosedSubtypeCodec.java | 3 +
.../fory/json/codec/GeneratedJsonSubtypeTable.java | 59 ++++
.../apache/fory/json/codec/JsonSubTypesInfo.java | 16 +-
.../json/resolver/JsonNativeSubtypeRegistry.java | 102 +++++++
.../fory/json/resolver/JsonSharedRegistry.java | 301 ++++++++++++++++++++-
.../fory/json/resolver/JsonTypeResolver.java | 84 +++++-
.../fory/json/resolver/SealedClassSupport.java | 31 +--
.../apache/fory/json/ForyJsonGraalVMFeature.java | 95 +++++--
.../fory/json/resolver/SealedClassSupport.java | 65 +++++
.../apache/fory/json/JsonSealedSubTypesTest.java | 236 ++++++++++++++++
...ypesTest_d_GeneratedShape_ForyJsonSubTypes.java | 41 ++-
.../kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt | 29 +-
.../json/kotlin/ksp/JavaSubtypeGenerationWriter.kt | 44 +++
.../apache/fory/json/kotlin/ksp/KspModelBuilder.kt | 229 +++++++++++++++-
.../org/apache/fory/json/kotlin/ksp/Model.kt | 8 +
.../apache/fory/json/kotlin/ksp/KspTestSupport.kt | 2 +
.../fory/json/kotlin/ksp/ProcessorResourceTest.kt | 38 ++-
.../fory/json/kotlin/KotlinJsonCodecFactory.kt | 13 +
.../fory/json/kotlin/KotlinSealedSubtypes.kt | 94 +++++++
.../fory/json/kotlin/KotlinSealedRuntimeTest.kt | 66 +++++
.../apache/fory/json/scala/ScalaJsonCodec.scala | 4 +-
.../scala/internal/DerivedScalaJsonCodec.scala | 38 ++-
.../json/scala/internal/ScalaJsonCodecMacros.scala | 42 ++-
.../scala/internal/ScalaTypeCodecFactory.scala | 10 +
.../fory/json/scala/ScalaJsonDerivationSuite.scala | 73 +++++
.../fory/json/scala/ScalaJsonNativeImageMain.scala | 16 +-
60 files changed, 2685 insertions(+), 378 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index 8329c0401..68c42bbb4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -200,11 +200,16 @@ This is the entry point for AI guidance in Apache Fory. Read this file first, th
"Unsupported" instead.
- After editing Markdown files outside `tasks/`, run `prettier --write <file>` on each changed Markdown file before finishing. Do not format Markdown under `tasks/`.
- User guide docs must explain user-visible behavior, commands, and examples.
- Do not add implementation details, internal ownership rationale, build flags,
- or type-id-space caveats unless they directly clarify a confusion users can
- act on. Translate internal owner-model details into concrete user actions, and
- avoid phrases such as "serializer-owned capability" or "registration alone
- does not..." in user-facing docs.
+ Do not expose implementation details unless readers must know them to choose an
+ API, configure a build, understand observable behavior, or resolve a documented
+ failure. Internal mechanisms such as metadata owners, generated tables,
+ processor handoffs, caches, reflection fallbacks, hosted discovery, and codegen
+ ownership belong in internal docs such as `docs/security/**`, source comments,
+ or task records. State required dependencies, platform versions,
+ configuration, and user-visible constraints directly without explaining the
+ internal mechanism that enforces them. If an implementation detail does not
+ change a concrete user action or supported behavior, omit it from user-facing
+ documentation.
- Add comments only when behavior is hard to understand or an algorithm is non-obvious.
- Do not remove existing code comments unless they are stale, misleading, redundant, or no longer necessary after the change.
- Only add tests that verify internal behaviors or fix specific bugs; do not create unnecessary tests unless requested.
diff --git a/ci/tasks/kotlin.py b/ci/tasks/kotlin.py
index a9a3ee111..d9f8b6d0c 100644
--- a/ci/tasks/kotlin.py
+++ b/ci/tasks/kotlin.py
@@ -35,13 +35,17 @@ CORPUS_RULE_MODELS = (
"PlatformAccount",
"PlatformBox",
"PlatformCircle",
+ "PlatformDirectOverride",
"PlatformId",
"PlatformMarker",
+ "PlatformOpen",
"PlatformRoot",
"PlatformShape",
+ "PlatformSquare",
)
CORPUS_MIXIN_TARGETS = {
"PlatformJavaProfileMixin": "PlatformJavaProfile",
+ "PlatformMixinOverrideAnnotations": "PlatformMixinOverride",
}
diff --git a/docs/json/android.md b/docs/json/android.md
index e0277f884..96db8a1c5 100644
--- a/docs/json/android.md
+++ b/docs/json/android.md
@@ -23,8 +23,9 @@ Fory JSON supports ordinary classes on Android API level 26 and later through th
`fory-json` artifact. Runtime JSON code generation and asynchronous compilation are disabled
automatically, so `ForyJson.builder().build()` uses the interpreted object mapper.
-Kotlin applications use the ordinary `fory-json-kotlin` runtime, which reads Kotlin/JVM metadata
-directly. KSP is needed only when R8 or ProGuard can rename or remove Kotlin model members.
+Kotlin applications use the ordinary `fory-json-kotlin` runtime. KSP is needed when R8 or ProGuard
+can rename or remove Kotlin model members or when a Kotlin-source Mixin adds inferred
+`JsonSubTypes` to a Java sealed target.
## Installation and Codec Model
@@ -48,8 +49,8 @@ dependencies {
}
```
-If the application enables R8 or ProGuard, also apply KSP 2.3.8 and add the retention-rule
-processor:
+If the application enables R8 or ProGuard, or if a Kotlin-source Mixin adds inferred `JsonSubTypes`
+to a Java sealed target, also apply KSP 2.3.8:
```kotlin
plugins {
@@ -63,8 +64,8 @@ dependencies {
Create the runtime with `ForyJsonKotlin.builder()`. For a minified build, annotate every required
Kotlin source model with `@JsonType`. For a third-party Kotlin target, declare a source-owned exact
-`@JsonMixin` instead. KSP emits exact R8 and ProGuard retention resources; it does not generate
-codecs or construction operations. Ensure those resources are packaged in the final application.
+`@JsonMixin` instead. If a Kotlin-source Mixin adds inferred `JsonSubTypes` to a Java sealed target,
+also apply `fory-annotation-processor` and compile on JDK 17 or newer.
## Custom Codecs
@@ -142,37 +143,33 @@ ForyJson json =
```
Compile a non-empty Java-source Mixin for a Java target with `fory-annotation-processor`. The
-processor emits exact R8 rules and any pair-specific target operations that the built `ForyJson`
-instance can use. Registered codecs, effective type codecs, and built-in mappings keep their normal
-codec-selection precedence. An empty Mixin produces no generated output.
+registered Mixin remains scoped to its exact target. Registered codecs, effective type codecs, and
+built-in mappings keep their normal codec-selection precedence.
A Mixin may place `JsonValidator` on a public abstract zero-argument `void` method that exactly
-matches a public target method. The generated pair calls that target method directly. The target
-does not need `JsonType` solely for a Mixin validator.
+matches a public target method. The target does not need `JsonType` solely for a Mixin validator.
-The target does not need `JsonType` merely because it has a Mixin. `JsonMixin` is itself the
-processor entry point for the pair. If a target also uses `JsonType`, the built `ForyJson` instance
-selects the pair-specific generated Java operations for a non-empty registered Mixin instead of
-combining the overlay with the target's directly generated operations.
+The target does not need `JsonType` merely because it has a Mixin. If the target also uses
+`JsonType`, the registered Mixin still defines the effective annotations for that `ForyJson`
+instance.
-Only one source is enabled for an exact target in one built `ForyJson` instance. A later registration for that
-target replaces an earlier registration on the builder, and `build()` snapshots the selected
-mapping. The processor may generate artifacts for multiple source alternatives; the built instance uses
-only the last registered source.
+Only one source is enabled for an exact target in one built `ForyJson` instance. A later
+registration for that target replaces an earlier registration on the builder, and `build()`
+snapshots the selected mapping.
-Use the processor-generated R8 rules for non-empty Mixins instead of broad package keep rules.
-
-If either the Mixin source or its exact target is Kotlin, process the source request with
-`fory-json-kotlin-ksp` instead. KSP emits only the exact retention rules for the target and Mixin.
+Use the Fory processors instead of broad package keep rules. A Java-only Mixin pair requires
+`fory-annotation-processor`; a pair involving Kotlin requires `fory-json-kotlin-ksp`. A
+Kotlin-source Mixin that adds inferred `JsonSubTypes` to a Java sealed target requires both and must
+be compiled on JDK 17 or newer.
## Reflection-Based Models
Ordinary non-Record classes that omit `JsonType` can supply equivalent exact rules themselves unless
-they declare `JsonValidator`. Direct validators require the processor-generated calls from
-`JsonType`; do not replace them with reflection rules. Retain every model constructor, field,
-method, generic signature, declaration annotation, and parameter annotation used by Fory JSON,
-plus the public no-argument constructor of every annotation-selected codec. For a model without a
-validator:
+they declare `JsonValidator`. Direct validators require `JsonType` and
+`fory-annotation-processor`; manual reflection rules are not sufficient. Retain every model
+constructor, field, method, generic signature, declaration annotation, and parameter annotation
+used by Fory JSON, plus the public no-argument constructor of every annotation-selected codec. For
+a model without a validator:
```proguard
-keepattributes Signature,RuntimeVisibleAnnotations,RuntimeVisibleParameterAnnotations
@@ -190,40 +187,38 @@ validator:
The same exact-rule approach supports every `JsonCodec` member; it is not limited to complete-value
codecs. `JsonType` is not required for codec selection on an ordinary class.
-This reflection-based section applies to Java models. Kotlin immutable models use validated
-Kotlin/JVM metadata on both the JVM and Android. For a minified Android build, use the Kotlin KSP
-processor to emit exact rules instead of writing broad package keep rules.
+This reflection-based section applies to Java models. Kotlin models use the Kotlin JSON module. For
+a minified Android build, apply KSP instead of writing broad package keep rules.
+
+Java `@JsonType` models support effective `JsonValidator`, `JsonValue`, `JsonRawValue`,
+`JsonBase64`, and `JsonFormat` annotations. Without `@JsonType`, those annotations still work
+through reflection, but a release-minified application must keep the exact annotated members,
+annotation attributes, and codec constructor itself. A `JsonValue` method may use a non-JavaBean
+name, so its manual rule must name that method explicitly.
-For Java `@JsonType` models, generated operations and R8 rules also cover effective
-`JsonValidator` methods, `JsonValue` fields and effective methods, fixed `JsonRawValue` and
-`JsonBase64` fields and getters, `JsonFormat` date/time fields, their runtime annotations, and the
-Base64 codec constructor. Without `@JsonType`, those annotations still work through reflection,
-but a release-minified application must keep the exact annotated members, annotation attributes,
-and codec constructor itself. A `JsonValue` method may use a non-JavaBean name, so its manual rule
-must name that method explicitly.
+Kotlin models use the same effective annotations. Enable KSP for minified builds. `JsonFormat` keeps
+the same direct-field and one-wrapper-level behavior as on the JVM, including `timezone` for
+`Instant`, `ZonedDateTime`, and `OffsetDateTime`.
-Kotlin models use the same effective annotations through metadata. The KSP retention rules preserve
-the corresponding constructors, accessors, fields, annotations, generic signatures, and compiler
-default operations in a minified build. `JsonFormat` keeps the same direct-field and
-one-wrapper-level behavior as on the JVM, including `timezone` for `Instant`, `ZonedDateTime`, and
-`OffsetDateTime`.
+Android supports inferred `JsonSubTypes` for Java and Kotlin sealed hierarchies. Java sealed
+inference requires `fory-annotation-processor` and JDK 17 or newer. Kotlin models in minified builds
+require `fory-json-kotlin-ksp`. For a Kotlin-source Mixin that adds inferred `JsonSubTypes` to a Java
+sealed target, apply both processors even when shrinking is disabled. Only the sealed hierarchy is
+considered; package and classpath subtype scanning are not supported.
Android Fory JSON requires a retained no-argument constructor for an ordinary mutable class; it may
be non-public when Android reflection can make it accessible. `JsonCreator` constructor-backed
classes follow the normal creator rules instead. Retain every field and method used for reflection,
or use an application codec when a model cannot satisfy those requirements. `JsonUnwrapped`
supports mutable classes, creator-backed classes, and Records through their normal property and
-construction paths. When the containing model and its unwrapped children use `JsonType`, their
-generated Java operations or Kotlin metadata supply those operations. A minified Kotlin build must
-also package the exact KSP retention rules for every Kotlin model in the path.
+construction paths. Apply the normal `JsonType` requirements to the containing model and every
+unwrapped child. In a minified Kotlin build, annotate each required model and enable KSP.
## Records
-Android-desugared Records require processor-generated operations from either a direct `@JsonType`
-declaration or a compiled exact `@JsonMixin` pair. Manual R8 rules alone cannot reconstruct Record
-component order because Android does not provide the Java Record reflection APIs. This also applies
-to a Record whose complete representation is a `JsonValue` String: the generated Java operations
-identify the propagated component accessor and call an annotated one-String canonical constructor
-directly. Generated child codecs act on one level exactly as they do on the JVM. Every Record in a
-`JsonUnwrapped` path needs its own direct `JsonType` declaration or compiled exact `JsonMixin` pair.
-Use a complete value codec for deeper nested behavior.
+Android-desugared Records require either a direct `@JsonType` declaration or an exact `@JsonMixin`
+processed by `fory-annotation-processor`. Manual R8 rules alone are insufficient because Android
+does not provide the Java Record reflection APIs. This also applies to a Record whose complete
+representation is a `JsonValue` String. Every Record in a `JsonUnwrapped` path needs its own direct
+`JsonType` declaration or processed exact `JsonMixin`. Child codecs act on one level exactly as they
+do on the JVM; use a complete value codec for deeper nested behavior.
diff --git a/docs/json/annotations.md b/docs/json/annotations.md
index 80bc6e98b..46353322b 100644
--- a/docs/json/annotations.md
+++ b/docs/json/annotations.md
@@ -27,23 +27,14 @@ Fory JSON provides these mapping and validation annotations in
Fory JSON APIs, not Jackson, Gson, or Fory binary-protocol compatibility annotations.
`JsonType` is not inherited, so mark each eligible concrete model that must participate in a
-platform build workflow. For Java source, the Fory annotation processor generates direct property
-and creator operations plus exact retention rules on the JVM and Android. A directly annotated
-`JsonValue` Record also receives generated value-access and canonical-constructor operations.
-Ordinary unannotated Java classes may still use reflection; on Android they need
-application-authored exact R8 rules. Android-desugared Records require processor-generated
-operations from either a direct `JsonType` declaration or a compiled exact `JsonMixin` pair.
-Outside Native Image, a directly annotated Java model that uses the default object codec fails
-during codec creation if its generated Java operations are missing.
-
-Kotlin/JVM models are mapped from validated Kotlin metadata and do not require generated
-construction operations. In Android builds that use R8 or ProGuard, Kotlin KSP emits exact
-retention rules for Kotlin `@JsonType` models. It also processes an exact Mixin declared in
-application source when either the Mixin or its exact target is Kotlin. KSP does not generate codecs
-or construction operations. GraalVM Native Image discovers reachable Java and Kotlin `JsonType`
-declarations directly. It generates codecs with the default configuration and each reachable
-provider configuration; models without a matching generated codec use interpreted codecs. See the
-[GraalVM guide](graalvm.md) and [Android guide](android.md) for the platform workflows.
+platform build workflow. For Java source, apply `fory-annotation-processor`. Ordinary unannotated
+Java classes may still use reflection; on Android they need application-authored exact R8 rules.
+Android-desugared Records require either a direct `JsonType` declaration or a compiled exact
+`JsonMixin` pair. Outside Native Image, a directly annotated Java model that uses the default object
+codec fails during codec creation if the annotation processor was not applied.
+
+Kotlin/JVM models use the Kotlin JSON module. See the [Kotlin guide](kotlin.md),
+[GraalVM guide](graalvm.md), and [Android guide](android.md) for platform setup.
## Kotlin use-site targets
@@ -127,10 +118,10 @@ A `JsonCodec` supplied by a Mixin is the target's effective annotation. An exact
`registerCodec` registration still wins, while the effective type annotation wins over a built-in
mapping.
-On Android, compile a Java-source Mixin for a Java target with the Fory annotation processor. If
-either the Mixin source or its exact target is Kotlin, apply the Kotlin KSP processor instead so the
-pair's exact retention rules are packaged. GraalVM Native Image discovers reachable Mixins
-directly. See the platform guides linked above.
+On Android, a Java-only Mixin pair requires `fory-annotation-processor`; a pair involving Kotlin
+requires `fory-json-kotlin-ksp`. A Kotlin-source Mixin that adds inferred `JsonSubTypes` to a Java
+sealed target requires both and must be compiled on JDK 17 or newer. See the platform guides linked
+above.
## `JsonProperty`
@@ -716,8 +707,9 @@ reflection configuration for validators.
## `JsonSubTypes`
-`JsonSubTypes` declares the complete finite subtype table for an interface or abstract class. Each
-entry has a case-sensitive logical JSON name and exactly one trusted Java type source:
+`JsonSubTypes` declares a finite subtype table for an interface or abstract class. A non-empty
+`value` is the complete explicit table. Each entry has a case-sensitive logical JSON name and
+exactly one trusted Java type source:
- `value = Circle.class`; or
- `className = "com.example.shape.Circle"` using the exact Java binary name.
@@ -726,6 +718,32 @@ entry has a case-sensitive logical JSON name and exactly one trusted Java type s
the fixed builder class loader when the table is built. JSON input never supplies a Java class name
and cannot add entries. Post-build subtype registration and open subtype discovery are not supported.
+Leave `value` empty to infer a sealed hierarchy:
+
+```java
+@JsonSubTypes(property = "kind")
+public sealed interface Shape permits Circle, Polygon {}
+
+public final class Circle implements Shape {}
+
+public sealed interface Polygon extends Shape permits Rectangle {}
+
+public final class Rectangle implements Polygon {}
+```
+
+Fory recursively traverses sealed abstract classes and interfaces. It adds every concrete class
+using its source simple name, including a concrete class that is itself sealed, and continues below
+a concrete sealed class. A concrete open or non-sealed class is added as one exact entry and its
+descendants are not admitted. An open abstract class or interface makes inference fail because that
+branch is not closed. Duplicate names and logical-name hash collisions also fail. These inferred
+names are wire names and are not transformed by the property naming strategy.
+
+Java sealed types require JDK 17 or newer. On Android, Java sealed inference also requires
+`fory-annotation-processor`, and minified Kotlin models require `fory-json-kotlin-ksp`. A
+Kotlin-source Mixin that adds inference to a Java sealed target requires both. Scala 3 sealed types
+use `derives ScalaJsonCodec` or builder derivation. Scala 2 sealed traits and classes are not
+inferred.
+
The default `PROPERTY` inclusion writes an inline discriminator as the first output member:
```java
@@ -789,12 +807,18 @@ Both wrappers may delegate to an exact custom subtype codec. All three inclusion
plain JSON null unless codec precedence selects a custom complete-value codec for the declared
base, replacing the annotation.
-The base must be an interface or abstract class. Every entry must resolve to a unique concrete,
-assignable class, and serialization accepts only an exact listed runtime class. Listing a parent
-does not implicitly admit its descendants. The annotation is read from the declared base itself and
-is not inherited from another annotated interface or abstract class. Readers accept only the
-configured inclusion; changing inclusion is a wire-format change and there is no dual-read
-fallback.
-
-At GraalVM native-image runtime, annotate the base with `JsonType` and use class-literal entries
-rather than `className` entries. Listed class-literal subtypes are registered automatically.
+The base must be an interface or abstract class. Every effective entry must be a unique concrete,
+assignable class, and serialization accepts only an exact table member. In an explicit table,
+listing a parent does not implicitly admit its descendants. The annotation is read from the
+declared base itself and is not inherited from another annotated interface or abstract class.
+Readers accept only the configured inclusion; changing inclusion is a wire-format change and there
+is no dual-read fallback.
+
+The selected top-level base authorizes its inferred static sealed closure. Use an explicit table
+when only a smaller subset should be available, or configure `JsonTypeChecker` to filter exact
+inferred candidates. The fixed disallow list must accept the complete inferred closure. An explicit
+table remains exact and fails if its entry conflicts with the checker.
+
+For GraalVM Native Image, annotate the base with `JsonType` when it is not otherwise reached from a
+provider root. Empty tables are supported for reachable Java, Kotlin, and Scala 3 sealed schemas.
+Explicit tables must use class-literal entries rather than `className`.
diff --git a/docs/json/getting-started.md b/docs/json/getting-started.md
index b3bb475c6..a1f001239 100644
--- a/docs/json/getting-started.md
+++ b/docs/json/getting-started.md
@@ -82,10 +82,11 @@ val text = json.toJson(User(7, "Alice"), userType)
val decoded = json.fromJson(text, userType)
```
-The runtime reads Kotlin/JVM metadata directly. Add `fory-json-kotlin-ksp` only to Android builds
-that use R8 or ProGuard; it emits exact retention rules for Kotlin `@JsonType` models and
-source-owned exact Mixins. GraalVM Native Image uses the normal `@ForyJsonProvider` workflow. The
-complete setup and Kotlin type behavior are in the [Kotlin JSON guide](kotlin.md).
+The Kotlin module does not require `kotlin-reflect`. On Android, add `fory-json-kotlin-ksp` when R8
+or ProGuard is enabled or when a Kotlin-source Mixin adds inferred `JsonSubTypes` to a Java sealed
+target. The Mixin case also requires `fory-annotation-processor` and JDK 17 or newer. GraalVM Native
+Image uses the normal `@ForyJsonProvider` workflow. The complete setup and Kotlin type behavior are
+in the [Kotlin JSON guide](kotlin.md).
### JDK 25 and later
diff --git a/docs/json/graalvm.md b/docs/json/graalvm.md
index 6cba20f3c..08295063c 100644
--- a/docs/json/graalvm.md
+++ b/docs/json/graalvm.md
@@ -180,17 +180,17 @@ built with.
## Type Discovery and Construction
-The `fory-json` artifact activates its Native Image Feature automatically. `@JsonType` is not
-inherited, so annotate every concrete application model. An annotated base with a class-literal
-`@JsonSubTypes` table registers its listed subtypes automatically. Dedicated supported containers,
-including `EnumMap` and `EnumSet`, use their built-in factories. Other reachable concrete
-`Collection` and `Map` root types require a public no-argument constructor. A class referenced only
-by a class name resolved at runtime is not reachable;
+No extra Native Image feature configuration is required. `@JsonType` is not inherited, so annotate
+every concrete application model. An annotated base with a class-literal `@JsonSubTypes` table
+registers its explicit or inferred subtypes automatically. Empty tables are supported for reachable
+Java, Kotlin, and Scala 3 sealed schemas. Other reachable concrete `Collection` and `Map` root types
+require a public no-argument constructor. A class referenced only by a class name resolved at
+runtime is not reachable;
`JsonSubTypes.Type.className` is therefore unsupported in a native image.
-Do not add application reflection configuration as a replacement for the generated configuration.
-The native executable resolves the same effective annotations as the JVM. Kotlin applications use
-the provider workflow above and must also avoid package-wide opens or reflection configuration.
+Do not add application reflection configuration. The native executable uses the same effective
+annotations as the JVM. Kotlin applications use the provider workflow above and must also avoid
+package-wide opens.
## Annotations and Custom Codecs
diff --git a/docs/json/kotlin.md b/docs/json/kotlin.md
index ab74b22fc..350dd4d04 100644
--- a/docs/json/kotlin.md
+++ b/docs/json/kotlin.md
@@ -45,9 +45,8 @@ dependencies {
}
```
-The runtime reads Kotlin/JVM metadata directly; do not add `kotlin-reflect`. KSP is not required for
-JVM applications or unminified Android builds. Android applications that use R8 or ProGuard should
-also apply KSP and add the retention-rule processor:
+The Kotlin module does not require `kotlin-reflect`. On Android, add KSP when R8 or ProGuard is
+enabled or when a Kotlin-source Mixin adds inferred `JsonSubTypes` to a Java sealed target:
```kotlin title="build.gradle.kts"
plugins {
@@ -61,8 +60,9 @@ dependencies {
Annotate every Kotlin source model that needs exact minification retention with `@JsonType`. For a
third-party target, declare an exact `@JsonMixin` in application source instead. Use Kotlin KSP for
-a Mixin when either the Mixin or its exact target is Kotlin. The processor emits only the exact R8
-and ProGuard rules for those declarations; it does not generate codecs or change the JSON mapping.
+a Mixin when either the Mixin or its exact target is Kotlin. If a Kotlin-source Mixin adds inferred
+`JsonSubTypes` to a Java sealed target, also enable `fory-annotation-processor` and compile on JDK 17
+or newer.
## Quick start
@@ -255,10 +255,12 @@ stateful object and a companion object require an exact custom codec. `Unit` als
`Nothing` is rejected, while `Nothing?` accepts only JSON null through its explicit Kotlin type
token.
-Sealed classes are not discovered from input or package metadata. Declare the complete logical-name
-table with `JsonSubTypes`; only listed exact runtime classes are accepted. The input contains a
-logical subtype name, never a JVM class name. See [Annotations](annotations.md#jsonsubtypes) for
-the available property and wrapper shapes.
+Annotate a sealed class or interface with `JsonSubTypes` and leave `value` empty to infer its closed
+hierarchy. Fory recursively includes concrete sealed descendants and stops at each concrete open
+class, admitting that exact class but not its descendants. An open abstract branch is rejected.
+Inferred logical names are source simple names, including object names without a trailing `$`. A
+non-empty `value` remains an exact explicit subset. Input contains a logical subtype name, never a
+JVM class name. See [Annotations](annotations.md#jsonsubtypes) for the property and wrapper shapes.
## Supported Kotlin types
@@ -289,7 +291,7 @@ Kotlin-specific behavior is:
| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- |
| ordinary, data, and nested classes | named JSON object |
| `inner` class, ordinary abstract class/interface | closed `JsonSubTypes` or exact custom codec only |
-| sealed class/interface | explicit closed `JsonSubTypes` table only |
+| sealed class/interface | inferred or explicit closed `JsonSubTypes` table |
| enum | quoted enum name |
| stateless `object`, `data object`, `Unit` | strict `{}` |
| stateful object, companion object | exact custom codec only |
@@ -326,7 +328,7 @@ API into a cross-version Kotlin guarantee.
`jsonTypeRef<T>()`, annotations, Mixins, and codec registrations are application-declared schema.
JSON input cannot select an arbitrary class, constructor, compiler default, object, companion,
module, codec, or callable. A sealed hierarchy accepts only the logical subtype names in its
-declared `@JsonSubTypes` table.
+validated inferred or explicit `@JsonSubTypes` table.
Kotlin arrays, collections, maps, and objects use the same `maxDepth`, graph-memory, input-buffer,
field-name-cache, and type-checker controls as the core JSON runtime. There are no Kotlin-specific
@@ -341,14 +343,15 @@ See [Security](security.md) before decoding untrusted input.
On GraalVM Native Image, use the existing `@ForyJsonProvider` workflow, install
`ForyJsonKotlin`, and enable code generation in the returned configuration. Annotate each reachable
concrete Kotlin model with `@JsonType`, or register an exact reachable Mixin for a third-party
-target. Fory reads the Kotlin metadata and adds generated codecs for each reachable Kotlin-enabled
-provider configuration while building the image. A model without a matching generated codec uses
-the interpreted codec. Only exact generic bindings reached through concrete roots are available.
-Do not add reflection configuration or package-wide opens.
-
-On Android, use API 26 or later. The runtime reads Kotlin metadata in both debug and release builds,
-and runtime JSON code generation remains disabled. Follow the [installation](#installation) above
-and the [Android guide](android.md) when R8 or ProGuard is enabled.
+target. Models not selected for code generation continue to use interpreted mapping. Only exact
+generic bindings reached through concrete roots are available. Do not add reflection configuration
+or package-wide opens.
+
+On Android, use API 26 or later. Runtime JSON code generation remains disabled. Kotlin sealed
+inference needs no additional setup in an unminified build. Enable KSP when R8 or ProGuard is used
+or when a Kotlin-source Mixin adds inferred `JsonSubTypes` to a Java sealed target. The Mixin case
+also requires `fory-annotation-processor` and JDK 17 or newer. Follow the
+[installation](#installation) above and the [Android guide](android.md) when shrinking is enabled.
Kotlin/Native, Kotlin/JS, and Kotlin/Wasm are not supported by this JVM module.
diff --git a/docs/json/scala.md b/docs/json/scala.md
index 3def6467b..18817d378 100644
--- a/docs/json/scala.md
+++ b/docs/json/scala.md
@@ -170,7 +170,7 @@ For a custom wire representation, extend `ScalaEnumerationCodec` and select the
`@JsonCodec`. The codec also implements the map-key contract, so its class can be used in
`keyCodec`.
-## Scala 3 closed enums
+## Scala 3 closed enums and sealed hierarchies
A parameterless Scala 3 enum uses its case name as a JSON string. Add `derives ScalaJsonCodec` to an
enum with parameterized cases to define one closed wrapper-object representation for every case:
@@ -196,6 +196,25 @@ builder call site:
val json = ForyJsonScala.builder().register[thirdparty.Result].build()
```
+For a Scala 3 sealed trait or class, add an empty `JsonSubTypes` annotation and derive
+`ScalaJsonCodec`:
+
+```scala
+import org.apache.fory.json.annotation.JsonSubTypes
+import org.apache.fory.json.scala.*
+
+@JsonSubTypes(property = "kind")
+sealed trait Event derives ScalaJsonCodec
+
+final case class Message(value: String) extends Event
+case object Idle extends Event
+```
+
+This example uses `Message` and `Idle` as logical subtype names. Derivation recursively traverses
+sealed branches. A concrete open class is one exact member and its descendants are not admitted; an
+open abstract branch is rejected. A non-empty annotation value remains an explicit subset. Scala 2
+sealed traits and classes are not supported by this inference feature.
+
### Packaging Derived Codecs in a Module
A library that supports several third-party Scala 3 enums can package their derived codecs in a
@@ -228,7 +247,7 @@ prevents an unrelated dependency from changing deserialization behavior. See
## GraalVM Native Image
-The Scala module uses the same build-time module registration on the JVM and in a native image.
-Application models, custom codecs, and derived enum schemas must be reachable when the native image
-is built. Generate Fory codecs as part of the native-image build rather than adding general
-reflection configuration. No Scala compiler, TASTy reader, or runtime macro execution is required.
+The Scala module uses the same registration on the JVM and in a native image. Application models,
+custom codecs, and derived enum or sealed schemas must be reachable when the native image is built.
+Generate Fory codecs as part of the native-image build rather than adding general reflection
+configuration.
diff --git a/docs/json/security.md b/docs/json/security.md
index 267c9f56d..deecb49d4 100644
--- a/docs/json/security.md
+++ b/docs/json/security.md
@@ -28,8 +28,8 @@ object surface.
Kotlin type tokens and metadata are trusted schema declarations, not input authority. The Kotlin
module validates the logical type, physical JVM carrier, and constructor/default operations before
parsing. JSON input cannot select a class, constructor, compiler default target, object, companion,
-module, codec, or callable. A closed `JsonSubTypes` value selects only a logical name from the
-application-declared finite table.
+module, codec, or callable. `JsonSubTypes` selects only a logical name from a finite table: either
+the explicit entries or the inferred sealed hierarchy.
## Type Policy And Class Loading
@@ -54,6 +54,14 @@ types normally do not invoke the custom checker, but an application codec for
a built-in target makes that target subject to the checker. A custom codec
never bypasses the fixed disallow list.
+An empty `JsonSubTypes.value` authorizes the statically sealed closure of the selected top-level
+base. This is still a closed set: JSON cannot name a class, search the classpath, or admit a later
+descendant of an exact open member. If the complete sealed closure is broader than the endpoint
+should trust, declare a non-empty explicit subtype table or use `withTypeChecker` to reject exact
+inferred classes. The fixed disallow list validates the complete inferred closure; the custom
+checker narrows that closure, and rejecting every inferred class is an error. Explicit subtype
+tables are exact declarations and fail if the checker rejects an entry.
+
`withClassLoader` sets the loader for annotation-declared subtype `className`
entries. Without it, `build()` snapshots the current thread context class
loader and falls back to the loader that defined `ForyJson`. Later changes to
diff --git a/docs/security/deserialization.md b/docs/security/deserialization.md
index 875eb0ff7..0e6fcd1f3 100644
--- a/docs/security/deserialization.md
+++ b/docs/security/deserialization.md
@@ -104,6 +104,21 @@ is not reached through an explicitly selected static root or a registered
enclosing owner, is serialization mechanics only and does not by itself
authorize a dynamically selected class.
+Java Fory JSON treats an explicitly selected top-level class with an empty
+`JsonSubTypes.value` as one static schema authorization. That declaration authorizes the finite
+concrete closure proven by Java sealed metadata, Kotlin metadata, or a Scala 3 derived codec. The
+schema is application or build input; JSON supplies only a logical subtype name and cannot supply a
+class name or extend the closure. A concrete open or non-sealed member authorizes that exact class,
+not its descendants. A non-empty `JsonSubTypes.value` instead authorizes exactly the declared
+subset.
+
+Fory's fixed disallow list must accept the complete inferred closure. An application
+`JsonTypeChecker` may narrow inferred metadata to the exact accepted concrete classes; rejecting
+all candidates is a schema error. The checker also remains authoritative for every entry in an
+explicit table. Materializing a class outside the resulting finite table, admitting a descendant
+of an exact open member, or bypassing either policy is security-relevant. Discovering and selecting
+an allowed member of that validated table is not open dynamic class resolution.
+
An application-provided custom deserialization policy is itself an application-owned trust
decision. In Python's reduce path, strict mode with the default policy requires registration-owned
authorization for a wire-selected global name before importing or resolving it. When an
diff --git a/integration_tests/android_tests/build.gradle b/integration_tests/android_tests/build.gradle
index 12e5f93c8..e4077ae2e 100644
--- a/integration_tests/android_tests/build.gradle
+++ b/integration_tests/android_tests/build.gradle
@@ -115,10 +115,13 @@ dependencies {
androidTestImplementation 'androidx.test:runner:1.6.2'
}
-def kotlinJsonRuleModels = [
- 'org.apache.fory.android.AndroidKotlinAccount',
- 'org.apache.fory.android.AndroidKotlinDefaults',
- 'org.apache.fory.android.AndroidKotlinMarker',
+def kotlinJsonRules = [
+ 'fory-json-org.apache.fory.android.AndroidKotlinAccount.pro':
+ 'org.apache.fory.android.AndroidKotlinAccount',
+ 'fory-json-org.apache.fory.android.AndroidKotlinDefaults.pro':
+ 'org.apache.fory.android.AndroidKotlinDefaults',
+ 'fory-json-org.apache.fory.android.AndroidKotlinMarker.pro':
+ 'org.apache.fory.android.AndroidKotlinMarker',
]
tasks.register('verifyKotlinJsonRules') {
@@ -128,9 +131,7 @@ tasks.register('verifyKotlinJsonRules') {
def ruleDir = layout.buildDirectory
.dir("generated/ksp/${variant}/resources/META-INF/proguard")
.get().asFile
- def expected = kotlinJsonRuleModels.collectEntries { model ->
- [("fory-json-${model}.pro"): model]
- }
+ def expected = kotlinJsonRules
def actual = fileTree(ruleDir).matching { include 'fory-json-*.pro' }.files
.collectEntries { rule -> [(rule.name): rule] }
if (actual.keySet() != expected.keySet()) {
@@ -145,6 +146,14 @@ tasks.register('verifyKotlinJsonRules') {
throw new GradleException("${actual[name]} does not retain exact model ${model}")
}
}
+ def request = layout.buildDirectory.file(
+ "generated/ksp/${variant}/java/org/apache/fory/android/" +
+ "AndroidKotlinJsonScenarios_d_KspJavaShapeMixin_" +
+ "ForyJsonSubtypeGeneration.java").get().asFile
+ if (!request.isFile() || !request.text.contains(
+ 'GeneratedJsonSubtypeTable.Generation')) {
+ throw new GradleException("Missing generated Java subtype request ${request}")
+ }
}
}
}
diff --git a/integration_tests/android_tests/proguard-rules.pro b/integration_tests/android_tests/proguard-rules.pro
index c3c4110c8..de5a0c2c6 100644
--- a/integration_tests/android_tests/proguard-rules.pro
+++ b/integration_tests/android_tests/proguard-rules.pro
@@ -19,12 +19,14 @@
public static void generatedCodecs();
public static void generatedUnwrapped();
public static void generatedMixin();
+ public static void generatedSealedMixin();
}
# Instrumentation invokes this entry point across the target/test APK boundary. KSP's exact
# consumer rules alone retain the Kotlin metadata and members used at runtime.
-keep,allowoptimization class org.apache.fory.android.AndroidKotlinJsonScenarios {
public static void metadataSurvivesMinification();
+ public static void javaSealedMixinSurvivesMinification();
}
# The release androidTest APK omits the Kotlin runtime shared with the separately minified target
diff --git a/integration_tests/android_tests/src/androidTest/java/org/apache/fory/android/ForyAndroidInstrumentedTest.java b/integration_tests/android_tests/src/androidTest/java/org/apache/fory/android/ForyAndroidInstrumentedTest.java
index 4d50298c1..f60128d1c 100644
--- a/integration_tests/android_tests/src/androidTest/java/org/apache/fory/android/ForyAndroidInstrumentedTest.java
+++ b/integration_tests/android_tests/src/androidTest/java/org/apache/fory/android/ForyAndroidInstrumentedTest.java
@@ -85,11 +85,21 @@ public class ForyAndroidInstrumentedTest {
AndroidJsonScenarios.generatedMixin();
}
+ @Test
+ public void generatedSealedJsonMixin() {
+ AndroidJsonScenarios.generatedSealedMixin();
+ }
+
@Test
public void kotlinJsonMetadataSurvivesMinification() {
AndroidKotlinJsonScenarios.metadataSurvivesMinification();
}
+ @Test
+ public void kotlinMixinForJavaSealedType() {
+ AndroidKotlinJsonScenarios.javaSealedMixinSurvivesMinification();
+ }
+
@Test
public void androidRuntimeDisablesCodegenAndUnsafeCopies() {
AndroidForyRuntimeScenarios.androidRuntimeDisablesCodegenAndUnsafeCopies();
diff --git a/integration_tests/android_tests/src/main/java/org/apache/fory/android/AndroidJsonScenarios.java b/integration_tests/android_tests/src/main/java/org/apache/fory/android/AndroidJsonScenarios.java
index a21c2e659..33d2b6a18 100644
--- a/integration_tests/android_tests/src/main/java/org/apache/fory/android/AndroidJsonScenarios.java
+++ b/integration_tests/android_tests/src/main/java/org/apache/fory/android/AndroidJsonScenarios.java
@@ -214,7 +214,7 @@ public final class AndroidJsonScenarios {
GeneratedJsonModel.resetCodecCalls();
String encoded = json.toJson(value, GeneratedJsonModel.class);
- check(encoded.contains("\"kind\":\"generated\""));
+ check(encoded.contains("\"kind\":\"GeneratedJsonSubtype\""));
check(encoded.contains("\"generated:list\""));
check(encoded.contains("\"generated:root\""));
check(encoded.contains("\"generated:property\""));
@@ -300,6 +300,16 @@ public final class AndroidJsonScenarios {
generatedMixinValueRecord();
}
+ public static void generatedSealedMixin() {
+ ForyJson json =
+ ForyJson.builder().registerMixin(GeneratedMixinShapeAnnotations.class).build();
+ String text = json.toJson(new GeneratedMixinShape.Circle(36), GeneratedMixinShape.class);
+ checkEquals("{\"kind\":\"Circle\",\"radius\":36}", text);
+ GeneratedMixinShape decoded = json.fromJson(text, GeneratedMixinShape.class);
+ check(decoded instanceof GeneratedMixinShape.Circle);
+ checkEquals(36, ((GeneratedMixinShape.Circle) decoded).radius);
+ }
+
private static void generatedMixinRecord() {
ForyJson json =
ForyJson.builder().registerMixin(GeneratedJsonMixinRecordAnnotations.class).build();
diff --git a/integration_tests/android_tests/src/main/java/org/apache/fory/android/GeneratedJsonModel.java b/integration_tests/android_tests/src/main/java/org/apache/fory/android/GeneratedJsonModel.java
index 3e6989109..a3030e3e5 100644
--- a/integration_tests/android_tests/src/main/java/org/apache/fory/android/GeneratedJsonModel.java
+++ b/integration_tests/android_tests/src/main/java/org/apache/fory/android/GeneratedJsonModel.java
@@ -58,12 +58,11 @@ abstract class GeneratedJsonBase<F, P> {
/** Processor-generated declaration-codec and R8 rule fixture. */
@JsonType
-@JsonSubTypes(
- property = "kind",
- value = {@JsonSubTypes.Type(value = GeneratedJsonSubtype.class, name = "generated")})
-public abstract class GeneratedJsonModel
+@JsonSubTypes(property = "kind")
+public abstract sealed class GeneratedJsonModel
extends GeneratedJsonBase<
- GeneratedJsonModel.DeclaredValue, GeneratedJsonModel.InheritedPropertyValue> {
+ GeneratedJsonModel.DeclaredValue, GeneratedJsonModel.InheritedPropertyValue>
+ permits GeneratedJsonSubtype {
private static final AtomicInteger CODEC_CALLS = new AtomicInteger();
private static final AtomicInteger KEY_CODEC_CALLS = new AtomicInteger();
diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt b/integration_tests/android_tests/src/main/java/org/apache/fory/android/GeneratedMixinShape.java
similarity index 56%
copy from kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
copy to integration_tests/android_tests/src/main/java/org/apache/fory/android/GeneratedMixinShape.java
index 6867ca8fb..88564ef88 100644
--- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
+++ b/integration_tests/android_tests/src/main/java/org/apache/fory/android/GeneratedMixinShape.java
@@ -17,30 +17,16 @@
* under the License.
*/
-package org.apache.fory.json.kotlin.ksp
+package org.apache.fory.android;
-import com.google.devtools.ksp.symbol.KSFile
+public sealed interface GeneratedMixinShape permits GeneratedMixinShape.Circle {
+ final class Circle implements GeneratedMixinShape {
+ public int radius;
-internal enum class MemberKind {
- FIELD,
- METHOD,
-}
-
-internal data class JvmMember(
- val kind: MemberKind,
- val ownerBinaryName: String,
- val name: String,
- val descriptor: String,
-)
+ public Circle() {}
-internal data class JsonModel(
- val targetBinaryName: String,
- val members: List<JvmMember>,
- val mixinBinaryName: String?,
- val originatingFiles: List<KSFile>,
- val retainedAnnotations: Set<String>,
- val annotationOwnerTypes: Set<String>,
- val retainedTypes: Set<String>,
- val codecTypes: Set<String>,
- val containerTypes: Set<String>,
-)
+ public Circle(int radius) {
+ this.radius = radius;
+ }
+ }
+}
diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt b/integration_tests/android_tests/src/main/java/org/apache/fory/android/GeneratedMixinShapeAnnotations.java
similarity index 56%
copy from kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
copy to integration_tests/android_tests/src/main/java/org/apache/fory/android/GeneratedMixinShapeAnnotations.java
index 6867ca8fb..213ad2932 100644
--- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
+++ b/integration_tests/android_tests/src/main/java/org/apache/fory/android/GeneratedMixinShapeAnnotations.java
@@ -17,30 +17,11 @@
* under the License.
*/
-package org.apache.fory.json.kotlin.ksp
+package org.apache.fory.android;
-import com.google.devtools.ksp.symbol.KSFile
+import org.apache.fory.json.annotation.JsonMixin;
+import org.apache.fory.json.annotation.JsonSubTypes;
-internal enum class MemberKind {
- FIELD,
- METHOD,
-}
-
-internal data class JvmMember(
- val kind: MemberKind,
- val ownerBinaryName: String,
- val name: String,
- val descriptor: String,
-)
-
-internal data class JsonModel(
- val targetBinaryName: String,
- val members: List<JvmMember>,
- val mixinBinaryName: String?,
- val originatingFiles: List<KSFile>,
- val retainedAnnotations: Set<String>,
- val annotationOwnerTypes: Set<String>,
- val retainedTypes: Set<String>,
- val codecTypes: Set<String>,
- val containerTypes: Set<String>,
-)
+@JsonMixin(target = GeneratedMixinShape.class)
+@JsonSubTypes(property = "kind")
+public interface GeneratedMixinShapeAnnotations {}
diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt b/integration_tests/android_tests/src/main/java/org/apache/fory/android/KspJavaShape.java
similarity index 56%
copy from kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
copy to integration_tests/android_tests/src/main/java/org/apache/fory/android/KspJavaShape.java
index 6867ca8fb..3f5f8e32a 100644
--- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
+++ b/integration_tests/android_tests/src/main/java/org/apache/fory/android/KspJavaShape.java
@@ -17,30 +17,16 @@
* under the License.
*/
-package org.apache.fory.json.kotlin.ksp
+package org.apache.fory.android;
-import com.google.devtools.ksp.symbol.KSFile
+public sealed interface KspJavaShape permits KspJavaShape.Circle {
+ final class Circle implements KspJavaShape {
+ public int radius;
-internal enum class MemberKind {
- FIELD,
- METHOD,
-}
-
-internal data class JvmMember(
- val kind: MemberKind,
- val ownerBinaryName: String,
- val name: String,
- val descriptor: String,
-)
+ public Circle() {}
-internal data class JsonModel(
- val targetBinaryName: String,
- val members: List<JvmMember>,
- val mixinBinaryName: String?,
- val originatingFiles: List<KSFile>,
- val retainedAnnotations: Set<String>,
- val annotationOwnerTypes: Set<String>,
- val retainedTypes: Set<String>,
- val codecTypes: Set<String>,
- val containerTypes: Set<String>,
-)
+ public Circle(int radius) {
+ this.radius = radius;
+ }
+ }
+}
diff --git a/integration_tests/android_tests/src/main/kotlin/org/apache/fory/android/AndroidKotlinJsonScenarios.kt b/integration_tests/android_tests/src/main/kotlin/org/apache/fory/android/AndroidKotlinJsonScenarios.kt
index a74814648..a36596d01 100644
--- a/integration_tests/android_tests/src/main/kotlin/org/apache/fory/android/AndroidKotlinJsonScenarios.kt
+++ b/integration_tests/android_tests/src/main/kotlin/org/apache/fory/android/AndroidKotlinJsonScenarios.kt
@@ -22,6 +22,8 @@ package org.apache.fory.android
import org.apache.fory.integration.kotlin.json.corpus.PlatformCorpusChecks
import org.apache.fory.integration.kotlin.json.corpus.PlatformJavaProfileMixin
import org.apache.fory.json.annotation.JsonType
+import org.apache.fory.json.annotation.JsonMixin
+import org.apache.fory.json.annotation.JsonSubTypes
import org.apache.fory.json.kotlin.ForyJsonKotlin
import org.apache.fory.json.kotlin.jsonTypeRef
@@ -73,6 +75,10 @@ internal data class AndroidKotlinDefaults(
)
internal object AndroidKotlinJsonScenarios {
+ @JsonMixin(target = KspJavaShape::class)
+ @JsonSubTypes(property = "kind")
+ private interface KspJavaShapeMixin
+
@JvmStatic
fun metadataSurvivesMinification() {
val json =
@@ -100,4 +106,13 @@ internal object AndroidKotlinJsonScenarios {
PlatformCorpusChecks.verifyRoundTrip(json)
}
+ @JvmStatic
+ fun javaSealedMixinSurvivesMinification() {
+ val json = ForyJsonKotlin.builder().registerMixin(KspJavaShapeMixin::class.java).build()
+ val text = json.toJson(KspJavaShape.Circle(37), KspJavaShape::class.java)
+ check(text == "{\"kind\":\"Circle\",\"radius\":37}")
+ val decoded = json.fromJson(text, KspJavaShape::class.java)
+ check(decoded is KspJavaShape.Circle && decoded.radius == 37)
+ }
+
}
diff --git a/integration_tests/graalvm_tests/src/main/java/org/apache/fory/graalvm/ForyJsonExample.java b/integration_tests/graalvm_tests/src/main/java/org/apache/fory/graalvm/ForyJsonExample.java
index c42816861..ff5055edf 100644
--- a/integration_tests/graalvm_tests/src/main/java/org/apache/fory/graalvm/ForyJsonExample.java
+++ b/integration_tests/graalvm_tests/src/main/java/org/apache/fory/graalvm/ForyJsonExample.java
@@ -95,6 +95,7 @@ public final class ForyJsonExample {
testCodecs();
testValueAnnotations();
testSubtypes();
+ testSubtypeMixin();
testContainerRoots();
testGenericProperties();
testUnwrapped();
@@ -137,6 +138,7 @@ public final class ForyJsonExample {
.registerCodec(CodegenProbeValue.class, new CodegenProbeCodec())
.registerMixin(CoreCompileStateMixin.class)
.registerMixin(EmptyMixin.class)
+ .registerMixin(SealedShapeMixin.class)
.registerMixin(StackTraceElementMixin.class)
.build();
}
@@ -507,6 +509,15 @@ public final class ForyJsonExample {
Preconditions.checkArgument(((Circle) decoded).radius == 9);
}
+ private static void testSubtypeMixin() {
+ ForyJson json = ForyJson.builder().registerMixin(SealedShapeMixin.class).build();
+ MixinShape value = new MixinCircle(7);
+ String encoded = json.toJson(value, MixinShape.class);
+ MixinShape decoded = json.fromJson(encoded, MixinShape.class);
+ Preconditions.checkArgument(decoded instanceof MixinCircle);
+ Preconditions.checkArgument(((MixinCircle) decoded).radius == 7);
+ }
+
private static void testContainerRoots() {
ForyJson json = ForyJson.builder().build();
StringList list = json.fromJson("[\"first\",\"second\"]", StringList.class);
@@ -1594,10 +1605,8 @@ public final class ForyJsonExample {
}
@JsonType
- @JsonSubTypes(
- property = "kind",
- value = {@JsonSubTypes.Type(value = Circle.class, name = "circle")})
- public interface Shape {}
+ @JsonSubTypes(property = "kind")
+ public sealed interface Shape permits Circle {}
public static final class Circle implements Shape {
public int radius;
@@ -1609,6 +1618,22 @@ public final class ForyJsonExample {
}
}
+ public sealed interface MixinShape permits MixinCircle {}
+
+ public static final class MixinCircle implements MixinShape {
+ public int radius;
+
+ public MixinCircle() {}
+
+ MixinCircle(int radius) {
+ this.radius = radius;
+ }
+ }
+
+ @JsonMixin(target = MixinShape.class)
+ @JsonSubTypes(property = "kind")
+ public interface SealedShapeMixin {}
+
@JsonType
public static final class SqlValues {
public Date date;
diff --git a/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt b/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt
index d64254ce6..865ad9ab0 100644
--- a/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt
+++ b/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt
@@ -21,6 +21,7 @@ package org.apache.fory.integration.kotlin.json.corpus
import kotlin.jvm.JvmInline
import org.apache.fory.json.annotation.JsonCodec
+import org.apache.fory.json.annotation.JsonMixin
import org.apache.fory.json.annotation.JsonSubTypes
import org.apache.fory.json.annotation.JsonType
import org.apache.fory.json.codec.AbstractJsonValueCodec
@@ -38,21 +39,20 @@ public data class PlatformAccount(
@JsonType @JvmInline public value class PlatformId(public val value: Long)
-@JsonType
-@JsonSubTypes(
- value =
- [
- JsonSubTypes.Type(value = PlatformCircle::class, name = "circle"),
- JsonSubTypes.Type(value = PlatformMarker::class, name = "marker"),
- ],
- property = "kind",
-)
-public sealed interface PlatformShape
+@JsonType @JsonSubTypes(property = "kind") public sealed interface PlatformShape
@JsonType public data class PlatformCircle(public val radius: Int) : PlatformShape
@JsonType public data object PlatformMarker : PlatformShape
+public sealed interface PlatformBranch : PlatformShape
+
+@JsonType public data class PlatformSquare(public val size: Int) : PlatformBranch
+
+@JsonType public open class PlatformOpen(public val value: Int) : PlatformShape
+
+public class PlatformOpenDescendant(value: Int) : PlatformOpen(value)
+
public data class PlatformToken(public val value: String)
public class PlatformTokenCodec : AbstractJsonValueCodec<PlatformToken>() {
@@ -66,6 +66,35 @@ public class PlatformTokenCodec : AbstractJsonValueCodec<PlatformToken>() {
}
}
+@JsonSubTypes
+@JsonCodec(PlatformDirectOverrideCodec::class)
+public data class PlatformDirectOverride(public val value: String)
+
+public class PlatformDirectOverrideCodec : AbstractJsonValueCodec<PlatformDirectOverride>() {
+ override fun write(writer: JsonWriter, value: PlatformDirectOverride?) {
+ if (value == null) writer.writeNull() else writer.writeString(value.value)
+ }
+
+ override fun read(reader: JsonReader): PlatformDirectOverride? =
+ reader.readString()?.let(::PlatformDirectOverride)
+}
+
+public data class PlatformMixinOverride(public val value: String)
+
+@JsonMixin(target = PlatformMixinOverride::class)
+@JsonSubTypes
+@JsonCodec(PlatformMixinOverrideCodec::class)
+public interface PlatformMixinOverrideAnnotations
+
+public class PlatformMixinOverrideCodec : AbstractJsonValueCodec<PlatformMixinOverride>() {
+ override fun write(writer: JsonWriter, value: PlatformMixinOverride?) {
+ if (value == null) writer.writeNull() else writer.writeString(value.value)
+ }
+
+ override fun read(reader: JsonReader): PlatformMixinOverride? =
+ reader.readString()?.let(::PlatformMixinOverride)
+}
+
@JsonType
public data class PlatformRoot(
public val account: PlatformAccount,
diff --git a/integration_tests/kotlin_json_corpus/src/main/resources/org/apache/fory/integration/kotlin/json/corpus/cases/root.json b/integration_tests/kotlin_json_corpus/src/main/resources/org/apache/fory/integration/kotlin/json/corpus/cases/root.json
index 38c051504..7a868b2a6 100644
--- a/integration_tests/kotlin_json_corpus/src/main/resources/org/apache/fory/integration/kotlin/json/corpus/cases/root.json
+++ b/integration_tests/kotlin_json_corpus/src/main/resources/org/apache/fory/integration/kotlin/json/corpus/cases/root.json
@@ -2,7 +2,7 @@
"account": { "id": 1, "name": "default" },
"id": 9,
"unsigned": 4294967295,
- "shape": { "kind": "circle", "radius": 3 },
+ "shape": { "kind": "PlatformCircle", "radius": 3 },
"profile": { "display_label": "mixin" },
"token": "custom",
"box": { "value": "generic" }
diff --git a/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt b/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt
index 251f8f431..acc1f1f8a 100644
--- a/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt
+++ b/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt
@@ -44,10 +44,21 @@ public class KspRetentionResourceTest {
val sealed = rules("PlatformShape")
assertTrue(sealed.contains("class $PACKAGE.PlatformCircle"), sealed)
assertTrue(sealed.contains("class $PACKAGE.PlatformMarker"), sealed)
+ assertTrue(sealed.contains("class $PACKAGE.PlatformSquare"), sealed)
+ assertTrue(sealed.contains("class $PACKAGE.PlatformOpen"), sealed)
+ assertFalse(sealed.contains("class $PACKAGE.PlatformOpenDescendant"), sealed)
assertConstructor(rules("PlatformRoot"), "$PACKAGE.PlatformTokenCodec")
+ assertConstructor(
+ rules("PlatformDirectOverride"),
+ "$PACKAGE.PlatformDirectOverrideCodec",
+ )
val mixin = mixinRules("PlatformJavaProfileMixin")
assertTrue(mixin.contains("class $PACKAGE.PlatformJavaProfile"), mixin)
assertTrue(mixin.contains("class $PACKAGE.PlatformJavaProfileMixin"), mixin)
+ assertConstructor(
+ mixinRules("PlatformMixinOverrideAnnotations"),
+ "$PACKAGE.PlatformMixinOverrideCodec",
+ )
outputs.forEach { output ->
val text = Files.readString(output)
@@ -88,11 +99,15 @@ public class KspRetentionResourceTest {
"META-INF/proguard/fory-json-$PACKAGE.PlatformAccount.pro",
"META-INF/proguard/fory-json-$PACKAGE.PlatformBox.pro",
"META-INF/proguard/fory-json-$PACKAGE.PlatformCircle.pro",
+ "META-INF/proguard/fory-json-$PACKAGE.PlatformDirectOverride.pro",
"META-INF/proguard/fory-json-$PACKAGE.PlatformId.pro",
"META-INF/proguard/fory-json-$PACKAGE.PlatformMarker.pro",
+ "META-INF/proguard/fory-json-$PACKAGE.PlatformOpen.pro",
"META-INF/proguard/fory-json-$PACKAGE.PlatformRoot.pro",
"META-INF/proguard/fory-json-$PACKAGE.PlatformShape.pro",
+ "META-INF/proguard/fory-json-$PACKAGE.PlatformSquare.pro",
"META-INF/proguard/fory-json-mixin-$PACKAGE.PlatformJavaProfileMixin.pro",
+ "META-INF/proguard/fory-json-mixin-$PACKAGE.PlatformMixinOverrideAnnotations.pro",
)
}
}
diff --git a/java/fory-annotation-processor/pom.xml b/java/fory-annotation-processor/pom.xml
index 05dbf4abe..352054648 100644
--- a/java/fory-annotation-processor/pom.xml
+++ b/java/fory-annotation-processor/pom.xml
@@ -40,6 +40,8 @@
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<fory.java.rootdir>${basedir}/..</fory.java.rootdir>
+ <fory.processor.mr.classes>${project.build.directory}/multi-release-classes</fory.processor.mr.classes>
+ <fory.processor.test.classes>${project.build.directory}/java17-test-classes</fory.processor.test.classes>
</properties>
<dependencies>
@@ -71,6 +73,127 @@
<proc>none</proc>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <configuration>
+ <archive>
+ <manifestEntries>
+ <Multi-Release>true</Multi-Release>
+ </manifestEntries>
+ </archive>
+ </configuration>
+ </plugin>
</plugins>
</build>
+
+ <profiles>
+ <profile>
+ <id>sealed-types-java17</id>
+ <activation><jdk>[17,)</jdk></activation>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-source-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-sources</id>
+ <phase>package</phase>
+ <goals><goal>jar</goal></goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <version>3.1.0</version>
+ <executions>
+ <execution>
+ <id>compile-java17-sealed-types</id>
+ <phase>process-classes</phase>
+ <goals><goal>run</goal></goals>
+ <configuration>
+ <target>
+ <delete dir="${fory.processor.mr.classes}/17"/>
+ <mkdir dir="${fory.processor.mr.classes}/17"/>
+ <javac srcdir="${project.basedir}/src/main/java17"
+ destdir="${fory.processor.mr.classes}/17"
+ includeantruntime="false" fork="true"
+ executable="${java.home}/bin/javac" debug="true">
+ <include name="org/**/*.java"/>
+ <classpath><pathelement location="${project.build.outputDirectory}"/></classpath>
+ <compilerarg value="--release"/><compilerarg value="17"/>
+ <compilerarg value="-sourcepath"/><compilerarg value=""/>
+ </javac>
+ </target>
+ </configuration>
+ </execution>
+ <execution>
+ <id>prepare-java17-test-classes</id>
+ <phase>process-test-classes</phase>
+ <goals><goal>run</goal></goals>
+ <configuration>
+ <target>
+ <delete dir="${fory.processor.test.classes}"/>
+ <mkdir dir="${fory.processor.test.classes}"/>
+ <copy todir="${fory.processor.test.classes}">
+ <fileset dir="${project.build.outputDirectory}"/>
+ </copy>
+ <copy todir="${fory.processor.test.classes}" overwrite="true">
+ <fileset dir="${fory.processor.mr.classes}/17"/>
+ </copy>
+ </target>
+ </configuration>
+ </execution>
+ <execution>
+ <id>inject-java17-sealed-types</id>
+ <phase>package</phase>
+ <goals><goal>run</goal></goals>
+ <configuration>
+ <target>
+ <jar destfile="${project.build.directory}/${project.build.finalName}.jar" update="true">
+ <zipfileset dir="${fory.processor.mr.classes}/17"
+ prefix="META-INF/versions/17" includes="**/*.class"/>
+ </jar>
+ </target>
+ </configuration>
+ </execution>
+ <execution>
+ <id>patch-multi-release-source-jar</id>
+ <phase>package</phase>
+ <goals><goal>run</goal></goals>
+ <configuration>
+ <skip>${maven.source.skip}</skip>
+ <target>
+ <property
+ name="multi.release.sources.jar"
+ value="${project.build.directory}/${project.build.finalName}-sources.jar"/>
+ <available
+ file="${multi.release.sources.jar}"
+ property="multi.release.sources.jar.present"/>
+ <fail
+ unless="multi.release.sources.jar.present"
+ message="Multi-release source patching requires ${multi.release.sources.jar}."/>
+ <jar destfile="${multi.release.sources.jar}" update="true">
+ <zipfileset dir="${project.basedir}/src/main/java17"
+ prefix="META-INF/versions/17">
+ <include name="**/*.java"/>
+ </zipfileset>
+ </jar>
+ </target>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <classesDirectory>${fory.processor.test.classes}</classesDirectory>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
</project>
diff --git a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/ForyStructProcessor.java b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/ForyStructProcessor.java
index 2c425fbfd..ec064aa62 100644
--- a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/ForyStructProcessor.java
+++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/ForyStructProcessor.java
@@ -79,6 +79,9 @@ public final class ForyStructProcessor extends AbstractProcessor {
private static final String JSON_TYPE = "org.apache.fory.json.annotation.JsonType";
private static final String JSON_MIXIN = "org.apache.fory.json.annotation.JsonMixin";
private static final String JSON_MIXIN_REMOVE = "org.apache.fory.json.annotation.JsonMixinRemove";
+ private static final String JSON_SUB_TYPES = "org.apache.fory.json.annotation.JsonSubTypes";
+ private static final String JSON_SUBTYPE_GENERATION =
+ "org.apache.fory.json.codec.GeneratedJsonSubtypeTable.Generation";
private static final String IGNORE = annotationClass("Ignore");
private static final String INT32_TYPE = annotationClass("Int32Type");
private static final String INT64_TYPE = annotationClass("Int64Type");
@@ -108,6 +111,8 @@ public final class ForyStructProcessor extends AbstractProcessor {
annotations.add(JSON_TYPE);
annotations.add(JSON_MIXIN);
annotations.add(JSON_MIXIN_REMOVE);
+ annotations.add(JSON_SUB_TYPES);
+ annotations.add(JSON_SUBTYPE_GENERATION);
return Collections.unmodifiableSet(annotations);
}
diff --git a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/GeneratedTypeNames.java b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/GeneratedTypeNames.java
index 157ad6b6d..ec67a48d7 100644
--- a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/GeneratedTypeNames.java
+++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/GeneratedTypeNames.java
@@ -41,6 +41,15 @@ final class GeneratedTypeNames {
+ escapeBinarySimpleName(targetBinaryName);
}
+ static String jsonSubtypeSimpleName(String binaryName) {
+ int packageSeparator = binaryName.lastIndexOf('.');
+ return escapeBinarySimpleName(binaryName.substring(packageSeparator + 1)) + "_ForyJsonSubTypes";
+ }
+
+ static String jsonMixinSubtypeSimpleName(String mixinBinaryName, String targetBinaryName) {
+ return jsonMixinSimpleName(mixinBinaryName, targetBinaryName) + "_ForyJsonSubTypes";
+ }
+
private static String escape(String value, boolean preserveDots) {
// Keep this encoding identical to fory-core GeneratedClassNames. The processor intentionally
// has no runtime dependency, so generated source names need this local build-time owner.
diff --git a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java
index e274e4573..eab6c6e54 100644
--- a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java
+++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java
@@ -65,6 +65,8 @@ final class JsonTypeProcessor {
private static final String JSON_MIXIN_REMOVE = JSON_PACKAGE + ".annotation.JsonMixinRemove";
private static final String JSON_CODEC = JSON_PACKAGE + ".annotation.JsonCodec";
private static final String JSON_SUB_TYPES = JSON_PACKAGE + ".annotation.JsonSubTypes";
+ private static final String JSON_SUBTYPE_GENERATION =
+ JSON_PACKAGE + ".codec.GeneratedJsonSubtypeTable.Generation";
private static final String JSON_CREATOR = JSON_PACKAGE + ".annotation.JsonCreator";
private static final String JSON_PROPERTY = JSON_PACKAGE + ".annotation.JsonProperty";
private static final String JSON_VALUE = JSON_PACKAGE + ".annotation.JsonValue";
@@ -102,15 +104,26 @@ final class JsonTypeProcessor {
void process(RoundEnvironment roundEnvironment) {
validateMixinControls(roundEnvironment);
+ collectSubtypeGenerations(roundEnvironment);
TypeElement jsonType = elements.getTypeElement(JSON_TYPE);
- if (jsonType == null) {
+ TypeElement jsonSubTypes = elements.getTypeElement(JSON_SUB_TYPES);
+ if (jsonType == null && jsonSubTypes == null) {
processMixins(roundEnvironment);
return;
}
Deque<TypeElement> pending = new ArrayDeque<>();
- for (Element element : roundEnvironment.getElementsAnnotatedWith(jsonType)) {
- if (element instanceof TypeElement) {
- pending.add((TypeElement) element);
+ if (jsonType != null) {
+ for (Element element : roundEnvironment.getElementsAnnotatedWith(jsonType)) {
+ if (element instanceof TypeElement) {
+ pending.add((TypeElement) element);
+ }
+ }
+ }
+ if (jsonSubTypes != null) {
+ for (Element element : roundEnvironment.getElementsAnnotatedWith(jsonSubTypes)) {
+ if (element instanceof TypeElement) {
+ pending.add((TypeElement) element);
+ }
}
}
while (!pending.isEmpty()) {
@@ -123,8 +136,11 @@ final class JsonTypeProcessor {
continue;
}
try {
+ AnnotationMirror subtypesAnnotation = annotationMirror(type, JSON_SUB_TYPES);
+ boolean typeCodec = codecSourceWriter.hasCompleteTypeCodec(type, null);
Model model = inspect(type);
- if (hasAnnotation(type, JSON_TYPE)) {
+ boolean inferred = !typeCodec && emptySubtypes(subtypesAnnotation);
+ if (!typeCodec && hasAnnotation(type, JSON_TYPE) && subtypesAnnotation == null) {
GeneratedJsonCodecSourceWriter.Result generated = codecSourceWriter.write(type);
if (generated != null) {
model.companionBinaryName = generated.companionBinaryName;
@@ -138,10 +154,26 @@ final class JsonTypeProcessor {
}
}
}
- List<TypeElement> subtypes = classLiteralSubtypes(type, model.binaryFallbackTypes);
+ List<TypeElement> subtypes;
+ if (typeCodec) {
+ subtypes = Collections.emptyList();
+ } else if (inferred) {
+ validateSubtypeRoot(type);
+ subtypes = sealedSubtypes(type);
+ model.subtypeTableBinaryName = emitSubtypeTable(type, null, subtypes);
+ model.nameTypes.add(model.binaryName);
+ mergeSubtypeModels(model, subtypes);
+ } else {
+ if (subtypesAnnotation != null) {
+ validateSubtypeRoot(type);
+ }
+ subtypes = classLiteralSubtypes(type, model.binaryFallbackTypes);
+ }
model.sort();
emitR8(model);
- pending.addAll(subtypes);
+ if (!inferred && !typeCodec) {
+ pending.addAll(subtypes);
+ }
} catch (GeneratedJsonCodecSourceWriter.InvalidJsonTypeException e) {
messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage(), e.element);
} catch (InvalidJsonTypeException e) {
@@ -156,6 +188,27 @@ final class JsonTypeProcessor {
processMixins(roundEnvironment);
}
+ private void collectSubtypeGenerations(RoundEnvironment roundEnvironment) {
+ TypeElement generationType = elements.getTypeElement(JSON_SUBTYPE_GENERATION);
+ if (generationType == null) {
+ return;
+ }
+ for (Element element : roundEnvironment.getElementsAnnotatedWith(generationType)) {
+ AnnotationMirror generation = annotationMirror(element, JSON_SUBTYPE_GENERATION);
+ AnnotationValue value = generation == null ? null : annotationValue(generation, "mixin");
+ TypeElement mixin =
+ value != null && value.getValue() instanceof String
+ ? elements.getTypeElement((String) value.getValue())
+ : null;
+ if (mixin == null) {
+ messager.printMessage(
+ Diagnostic.Kind.ERROR, "Cannot resolve generated JSON subtype Mixin", element);
+ continue;
+ }
+ pendingMixins.put(elements.getBinaryName(mixin).toString(), mixin);
+ }
+ }
+
private void validateMixinControls(RoundEnvironment roundEnvironment) {
TypeElement removeType = elements.getTypeElement(JSON_MIXIN_REMOVE);
if (removeType == null) {
@@ -223,11 +276,15 @@ final class JsonTypeProcessor {
if (annotations.isEmpty()) {
continue;
}
+ AnnotationMirror subtypesAnnotation = annotationMirror(annotations, target, JSON_SUB_TYPES);
+ boolean inferred = emptySubtypes(subtypesAnnotation);
boolean directTypeCodec = codecSourceWriter.hasDirectTypeCodec(target, annotations);
boolean typeCodec =
directTypeCodec || codecSourceWriter.hasCompleteTypeCodec(target, annotations);
GeneratedJsonCodecSourceWriter.Result generated =
- typeCodec ? null : codecSourceWriter.writePair(annotations);
+ typeCodec || subtypesAnnotation != null
+ ? null
+ : codecSourceWriter.writePair(annotations);
Model model =
typeCodec
? inspectTypeCodec(target, annotations, directTypeCodec)
@@ -250,7 +307,19 @@ final class JsonTypeProcessor {
}
}
if (!typeCodec) {
- collectPairClosure(model, target, annotations);
+ if (inferred) {
+ validateSubtypeRoot(target);
+ List<TypeElement> subtypes = sealedSubtypes(target);
+ model.subtypeTableBinaryName = emitSubtypeTable(target, mixin, subtypes);
+ model.nameTypes.add(model.binaryName);
+ model.nameTypes.add(mixinBinaryName);
+ mergeSubtypeModels(model, subtypes);
+ } else {
+ if (subtypesAnnotation != null) {
+ validateSubtypeRoot(target);
+ }
+ collectPairClosure(model, target, annotations);
+ }
}
model.sort();
emitR8(model);
@@ -646,6 +715,17 @@ final class JsonTypeProcessor {
}
builder.append("}\n");
}
+ if (model.subtypeTableBinaryName != null) {
+ builder
+ .append("-keep,allowoptimization class ")
+ .append(model.subtypeTableBinaryName)
+ .append(" {\n")
+ .append(" public <init>();\n")
+ .append(" public java.lang.Class type();\n")
+ .append(" public java.lang.Class[] subtypes();\n")
+ .append(" public java.lang.String[] names();\n")
+ .append("}\n");
+ }
return builder.toString();
}
@@ -692,6 +772,187 @@ final class JsonTypeProcessor {
return subtypesToProcess;
}
+ private boolean emptySubtypes(AnnotationMirror annotation) {
+ if (annotation == null) {
+ return false;
+ }
+ AnnotationValue value = annotationValue(annotation, "value");
+ return value != null
+ && value.getValue() instanceof List<?>
+ && ((List<?>) value.getValue()).isEmpty();
+ }
+
+ private void validateSubtypeRoot(TypeElement root) {
+ if (!root.getKind().isInterface() && !root.getModifiers().contains(Modifier.ABSTRACT)) {
+ throw new InvalidJsonTypeException(
+ "@JsonSubTypes requires an interface or abstract type", root);
+ }
+ }
+
+ private List<TypeElement> sealedSubtypes(TypeElement root) {
+ if (!SealedTypeSupport.isSealed(root)) {
+ throw new InvalidJsonTypeException(
+ "Empty @JsonSubTypes requires a sealed Java type; run the processor on JDK 17 or newer",
+ root);
+ }
+ List<TypeElement> result = new ArrayList<>();
+ Set<String> visited = new HashSet<>();
+ collectSealedSubtypes(root, result, visited);
+ if (result.isEmpty()) {
+ throw new InvalidJsonTypeException("Sealed JSON hierarchy has no concrete subtype", root);
+ }
+ result.sort(Comparator.comparing(type -> elements.getBinaryName(type).toString()));
+ Set<String> names = new HashSet<>();
+ Set<Long> hashes = new HashSet<>();
+ for (TypeElement subtype : result) {
+ String name = subtype.getSimpleName().toString();
+ if (!names.add(name)) {
+ throw new InvalidJsonTypeException("Duplicate inferred JSON subtype name " + name, subtype);
+ }
+ if (!hashes.add(Long.valueOf(jsonNameHash(name)))) {
+ throw new InvalidJsonTypeException(
+ "Inferred JSON subtype name hash collision for " + name, subtype);
+ }
+ }
+ return result;
+ }
+
+ private void collectSealedSubtypes(
+ TypeElement sealedType, List<TypeElement> result, Set<String> visited) {
+ List<? extends TypeElement> direct = SealedTypeSupport.directSubtypes(sealedType);
+ if (direct == null) {
+ throw new InvalidJsonTypeException(
+ "Sealed Java metadata is unavailable; run the processor on JDK 17 or newer", sealedType);
+ }
+ for (TypeElement subtype : direct) {
+ String binaryName = elements.getBinaryName(subtype).toString();
+ if (!visited.add(binaryName)) {
+ continue;
+ }
+ boolean concrete =
+ subtype.getKind().isClass() && !subtype.getModifiers().contains(Modifier.ABSTRACT);
+ if (concrete) {
+ validateSubtypeAccess(sealedType, subtype);
+ result.add(subtype);
+ }
+ if (SealedTypeSupport.isSealed(subtype)) {
+ collectSealedSubtypes(subtype, result, visited);
+ } else if (!concrete) {
+ throw new InvalidJsonTypeException(
+ "Sealed JSON hierarchy has an open abstract branch " + binaryName, subtype);
+ }
+ }
+ }
+
+ private void validateSubtypeAccess(TypeElement root, TypeElement subtype) {
+ String generatedPackage = elements.getPackageOf(root).getQualifiedName().toString();
+ String subtypePackage = elements.getPackageOf(subtype).getQualifiedName().toString();
+ for (Element current = subtype;
+ current instanceof TypeElement;
+ current = current.getEnclosingElement()) {
+ Set<Modifier> modifiers = current.getModifiers();
+ if (modifiers.contains(Modifier.PRIVATE)
+ || !generatedPackage.equals(subtypePackage) && !modifiers.contains(Modifier.PUBLIC)) {
+ throw new InvalidJsonTypeException(
+ "Generated subtype table cannot access " + elements.getBinaryName(subtype), subtype);
+ }
+ }
+ }
+
+ private void mergeSubtypeModels(Model model, List<TypeElement> subtypes) {
+ for (TypeElement subtype : subtypes) {
+ Model child = inspectModel(subtype, null);
+ model.merge(child);
+ }
+ }
+
+ private String emitSubtypeTable(
+ TypeElement target, TypeElement mixin, List<TypeElement> subtypes) {
+ TypeElement owner = mixin == null ? target : mixin;
+ PackageElement packageElement = elements.getPackageOf(owner);
+ String packageName =
+ packageElement.isUnnamed() ? "" : packageElement.getQualifiedName().toString();
+ String targetBinaryName = elements.getBinaryName(target).toString();
+ String simpleName =
+ mixin == null
+ ? GeneratedTypeNames.jsonSubtypeSimpleName(targetBinaryName)
+ : GeneratedTypeNames.jsonMixinSubtypeSimpleName(
+ elements.getBinaryName(mixin).toString(), targetBinaryName);
+ String generatedName = packageName.isEmpty() ? simpleName : packageName + "." + simpleName;
+ List<Element> origins = new ArrayList<>();
+ origins.add(owner);
+ if (owner != target) {
+ origins.add(target);
+ }
+ origins.addAll(subtypes);
+ validateSubtypeAccess(owner, target);
+ for (TypeElement subtype : subtypes) {
+ validateSubtypeAccess(owner, subtype);
+ }
+ try {
+ javax.tools.JavaFileObject file =
+ filer.createSourceFile(generatedName, origins.toArray(new Element[0]));
+ try (Writer writer = file.openWriter()) {
+ if (!packageName.isEmpty()) {
+ writer.write("package " + packageName + ";\n\n");
+ }
+ writer.write(
+ "public final class "
+ + simpleName
+ + " implements org.apache.fory.json.codec.GeneratedJsonSubtypeTable {\n");
+ writer.write(" public " + simpleName + "() {}\n");
+ writer.write(
+ " public java.lang.Class<?> type() { return "
+ + target.getQualifiedName()
+ + ".class; }\n");
+ writer.write(
+ " public java.lang.Class<?>[] subtypes() { return new java.lang.Class<?>[] {");
+ for (int i = 0; i < subtypes.size(); i++) {
+ if (i != 0) {
+ writer.write(", ");
+ }
+ writer.write(subtypes.get(i).getQualifiedName() + ".class");
+ }
+ writer.write("}; }\n");
+ writer.write(" public java.lang.String[] names() { return new java.lang.String[] {");
+ for (int i = 0; i < subtypes.size(); i++) {
+ if (i != 0) {
+ writer.write(", ");
+ }
+ writer.write("\"" + subtypes.get(i).getSimpleName() + "\"");
+ }
+ writer.write("}; }\n}\n");
+ }
+ return generatedName;
+ } catch (IOException e) {
+ throw new InvalidJsonTypeException(
+ "Failed to write generated JSON subtype table: " + e, owner);
+ }
+ }
+
+ private static long jsonNameHash(String name) {
+ if (!name.isEmpty() && name.length() <= Long.BYTES) {
+ boolean latin1 = true;
+ long value = 0;
+ for (int i = 0; i < name.length(); i++) {
+ char ch = name.charAt(i);
+ if (ch > 0xFF || ch == 0) {
+ latin1 = false;
+ break;
+ }
+ value |= ((long) ch) << (i << 3);
+ }
+ if (latin1 && value != 0) {
+ return value;
+ }
+ }
+ long hash = 0xcbf29ce484222325L;
+ for (int i = 0; i < name.length(); i++) {
+ hash = (hash ^ name.charAt(i)) * 0x100000001b3L;
+ }
+ return hash;
+ }
+
private void collectPairClosure(
Model model, TypeElement target, JsonMixinAnnotations annotations) {
Set<String> visited = new HashSet<>();
@@ -1141,10 +1402,12 @@ final class JsonTypeProcessor {
final Set<String> binaryFallbackTypes = new LinkedHashSet<>();
final Set<String> annotationOwnerTypes = new LinkedHashSet<>();
final Set<String> nameTypes = new LinkedHashSet<>();
+ final Set<TypeElement> originatingTypes = new LinkedHashSet<>();
JsonMixinAnnotations annotations;
TypeElement mixin;
String resourceIdentity;
String companionBinaryName;
+ String subtypeTableBinaryName;
boolean companionHasAnySetter;
boolean companionHasCreator;
boolean companionHasCreatorFactory;
@@ -1155,6 +1418,7 @@ final class JsonTypeProcessor {
this.target = target;
this.binaryName = binaryName;
resourceIdentity = binaryName;
+ originatingTypes.add(target);
}
void addR8Member(R8Member member) {
@@ -1193,10 +1457,16 @@ final class JsonTypeProcessor {
binaryFallbackTypes.addAll(other.binaryFallbackTypes);
annotationOwnerTypes.addAll(other.annotationOwnerTypes);
nameTypes.addAll(other.nameTypes);
+ originatingTypes.addAll(other.originatingTypes);
}
Element[] originatingElements() {
- return mixin == null ? new Element[] {target} : new Element[] {mixin, target};
+ List<Element> elements = new ArrayList<>();
+ if (mixin != null) {
+ elements.add(mixin);
+ }
+ elements.addAll(originatingTypes);
+ return elements.toArray(new Element[0]);
}
private static boolean containsNested(Set<String> names) {
diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/SealedTypeSupport.java
similarity index 56%
copy from kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
copy to java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/SealedTypeSupport.java
index 6867ca8fb..7e6db003a 100644
--- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
+++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/SealedTypeSupport.java
@@ -17,30 +17,20 @@
* under the License.
*/
-package org.apache.fory.json.kotlin.ksp
+package org.apache.fory.annotation.processing;
-import com.google.devtools.ksp.symbol.KSFile
+import java.util.List;
+import javax.lang.model.element.TypeElement;
-internal enum class MemberKind {
- FIELD,
- METHOD,
-}
+/** Java 8 annotation-processing baseline for sealed type metadata. */
+final class SealedTypeSupport {
+ private SealedTypeSupport() {}
-internal data class JvmMember(
- val kind: MemberKind,
- val ownerBinaryName: String,
- val name: String,
- val descriptor: String,
-)
+ static boolean isSealed(TypeElement type) {
+ return false;
+ }
-internal data class JsonModel(
- val targetBinaryName: String,
- val members: List<JvmMember>,
- val mixinBinaryName: String?,
- val originatingFiles: List<KSFile>,
- val retainedAnnotations: Set<String>,
- val annotationOwnerTypes: Set<String>,
- val retainedTypes: Set<String>,
- val codecTypes: Set<String>,
- val containerTypes: Set<String>,
-)
+ static List<? extends TypeElement> directSubtypes(TypeElement type) {
+ return null;
+ }
+}
diff --git a/java/fory-annotation-processor/src/main/java17/org/apache/fory/annotation/processing/SealedTypeSupport.java b/java/fory-annotation-processor/src/main/java17/org/apache/fory/annotation/processing/SealedTypeSupport.java
new file mode 100644
index 000000000..05c6ca3df
--- /dev/null
+++ b/java/fory-annotation-processor/src/main/java17/org/apache/fory/annotation/processing/SealedTypeSupport.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.fory.annotation.processing;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.type.TypeMirror;
+
+/** Java 17 annotation-processing access to sealed source metadata. */
+final class SealedTypeSupport {
+ private SealedTypeSupport() {}
+
+ static boolean isSealed(TypeElement type) {
+ return type.getModifiers().contains(Modifier.SEALED);
+ }
+
+ static List<? extends TypeElement> directSubtypes(TypeElement type) {
+ List<TypeElement> result = new ArrayList<>();
+ for (TypeMirror subtype : type.getPermittedSubclasses()) {
+ if (subtype instanceof javax.lang.model.type.DeclaredType) {
+ result.add((TypeElement) ((javax.lang.model.type.DeclaredType) subtype).asElement());
+ }
+ }
+ return result;
+ }
+}
diff --git a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java
index 31516917b..8aac74e26 100644
--- a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java
+++ b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java
@@ -1682,6 +1682,139 @@ public class JsonTypeProcessorTest {
assertTrue(rules.contains("-keep,allowoptimization class external.HiddenChild"), rules);
}
+ @Test
+ public void inferredSubtypeTable() throws Exception {
+ assumeJava17Source();
+ CompilationResult result =
+ compile(
+ "test.Shape",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.JsonSubTypes;\n"
+ + "@JsonSubTypes(property = \"kind\")\n"
+ + "public sealed interface Shape permits Shape.Circle, Shape.Branch, Shape.Open {\n"
+ + " final class Circle implements Shape { public int value; public Circle() {} }\n"
+ + " sealed abstract class Branch implements Shape permits Branch.Leaf {\n"
+ + " public static final class Leaf extends Branch { public int value; public Leaf() {} }\n"
+ + " }\n"
+ + " non-sealed class Open implements Shape { public int value; public Open() {} }\n"
+ + "}\n");
+ assertTrue(result.success, result.diagnostics());
+ String generated = "test/Shape_ForyJsonSubTypes.java";
+ assertTrue(result.hasGeneratedSource(generated));
+ String source = result.generatedSource(generated);
+ assertTrue(source.contains("Shape.Branch.Leaf.class"), source);
+ assertTrue(source.contains("Shape.Circle.class"), source);
+ assertTrue(source.contains("Shape.Open.class"), source);
+ String rules = result.generatedResource(RULE_PREFIX + "test.Shape.pro");
+ assertTrue(rules.contains("-keep,allowoptimization class test.Shape\n"), rules);
+ assertTrue(rules.contains("class test.Shape_ForyJsonSubTypes"), rules);
+ assertTrue(rules.contains("int value;"), rules);
+
+ ClassLoader loader = result.classLoader();
+ Class<?> root = loader.loadClass("test.Shape");
+ Class<?> circle = loader.loadClass("test.Shape$Circle");
+ Object value = circle.getConstructor().newInstance();
+ circle.getField("value").setInt(value, 3);
+ for (ForyJson json : jsonRuntimes(loader)) {
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ String text = json.toJson(value, (Class) root);
+ assertEquals(text, "{\"kind\":\"Circle\",\"value\":3}");
+ assertEquals(json.fromJson(text, root).getClass(), circle);
+ }
+ }
+
+ @Test
+ public void customCodecOverridesInferredSubtypes() throws Exception {
+ CompilationResult result =
+ compile(
+ "test.CustomShape",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "@JsonSubTypes(property = \"kind\")\n"
+ + "@JsonCodec(CustomShape.Codec.class) public final class CustomShape {\n"
+ + valueCodec("Codec")
+ + "}\n");
+ assertTrue(result.success, result.diagnostics());
+ assertFalse(result.hasGeneratedSource("test/CustomShape_ForyJsonSubTypes.java"));
+ String rules = result.generatedResource(RULE_PREFIX + "test.CustomShape.pro");
+ assertTrue(rules.contains("class test.CustomShape$Codec { public <init>(); }"), rules);
+ }
+
+ @Test
+ public void inferredMixinTable() throws Exception {
+ assumeJava17Source();
+ CompilationResult result =
+ compile(
+ "test.MixinShape",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "public sealed interface MixinShape permits MixinShape.Value {\n"
+ + " final class Value implements MixinShape { public int id; public Value() {} }\n"
+ + "}\n"
+ + "@JsonMixin(target = MixinShape.class)\n"
+ + "@JsonSubTypes(property = \"kind\") interface ShapeMixin {}\n");
+ assertTrue(result.success, result.diagnostics());
+ String table = "test/ShapeMixin_ForyJsonMixin_test_x2e_MixinShape_ForyJsonSubTypes.java";
+ assertTrue(result.hasGeneratedSource(table));
+ String rules = result.generatedResource(MIXIN_RULE_PREFIX + "test.ShapeMixin.pro");
+ assertTrue(rules.contains("-keep,allowoptimization class test.MixinShape\n"), rules);
+ assertTrue(rules.contains("-keep,allowoptimization class test.ShapeMixin\n"), rules);
+ ClassLoader loader = result.classLoader();
+ Class<?> root = loader.loadClass("test.MixinShape");
+ Class<?> valueType = loader.loadClass("test.MixinShape$Value");
+ Class<?> mixin = loader.loadClass("test.ShapeMixin");
+ Object value = valueType.getConstructor().newInstance();
+ valueType.getField("id").setInt(value, 4);
+ for (boolean codegen : new boolean[] {false, true}) {
+ ForyJson json =
+ ForyJson.builder()
+ .withCodegen(codegen)
+ .withAsyncCompilation(false)
+ .withClassLoader(loader)
+ .registerMixin(mixin)
+ .build();
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ String text = json.toJson(value, (Class) root);
+ assertEquals(text, "{\"kind\":\"Value\",\"id\":4}");
+ assertEquals(json.fromJson(text, root).getClass(), valueType);
+ }
+ }
+
+ @Test
+ public void rejectOpenAbstractSubtype() throws Exception {
+ assumeJava17Source();
+ CompilationResult result =
+ compile(
+ "test.InvalidShape",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.JsonSubTypes;\n"
+ + "@JsonSubTypes(property = \"kind\")\n"
+ + "public sealed interface InvalidShape permits OpenBranch {}\n"
+ + "non-sealed abstract class OpenBranch implements InvalidShape {}\n");
+ assertFalse(result.success);
+ assertTrue(
+ result.diagnostics().contains("open abstract branch test.OpenBranch"),
+ result.diagnostics());
+ }
+
+ @Test
+ public void rejectInaccessibleSubtypeRoot() throws Exception {
+ assumeJava17Source();
+ CompilationResult result =
+ compile(
+ "test.Container",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.JsonSubTypes;\n"
+ + "public class Container {\n"
+ + " @JsonSubTypes private sealed interface Root permits Leaf {}\n"
+ + " public static final class Leaf implements Root {}\n"
+ + "}\n");
+ assertFalse(result.success);
+ assertTrue(
+ result.diagnostics().contains("Generated subtype table cannot access test.Container$Root"),
+ result.diagnostics());
+ }
+
@Test
public void enumRules() throws Exception {
CompilationResult result =
@@ -2054,6 +2187,20 @@ public class JsonTypeProcessorTest {
}
}
+ private static void assumeJava17Source() {
+ String version = System.getProperty("java.specification.version");
+ if (version.startsWith("1.")) {
+ version = version.substring(2);
+ }
+ int dotIndex = version.indexOf('.');
+ if (dotIndex >= 0) {
+ version = version.substring(0, dotIndex);
+ }
+ if (Integer.parseInt(version) < 17) {
+ throw new SkipException("Source test requires JDK 17 or newer");
+ }
+ }
+
private static final class CompilationResult {
final Path classRoot;
final Path generatedRoot;
@@ -2079,6 +2226,11 @@ public class JsonTypeProcessorTest {
return Files.exists(classRoot.resolve(relativePath));
}
+ String generatedSource(String relativePath) throws IOException {
+ return new String(
+ Files.readAllBytes(generatedRoot.resolve(relativePath)), StandardCharsets.UTF_8);
+ }
+
String generatedResource(String relativePath) throws IOException {
return new String(
Files.readAllBytes(classRoot.resolve(relativePath)), StandardCharsets.UTF_8);
diff --git a/java/fory-json/pom.xml b/java/fory-json/pom.xml
index 622847610..a8ba16958 100644
--- a/java/fory-json/pom.xml
+++ b/java/fory-json/pom.xml
@@ -194,6 +194,9 @@
<exclude name="module-info.class"/>
</fileset>
</copy>
+ <copy todir="${fory.json.java9.test.classes}" overwrite="true">
+ <fileset dir="${fory.json.mr.classes}/17" erroronmissingdir="false"/>
+ </copy>
</target>
</configuration>
</execution>
@@ -263,6 +266,35 @@
</target>
</configuration>
</execution>
+ <execution>
+ <id>compile-java17-tests</id>
+ <phase>test-compile</phase>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ <configuration>
+ <skip>${maven.test.skip}</skip>
+ <target>
+ <javac srcdir="${project.basedir}/src/test/java17"
+ destdir="${project.build.testOutputDirectory}"
+ includeantruntime="false"
+ fork="true"
+ executable="${java.home}/bin/javac"
+ debug="true">
+ <include name="org/**/*.java"/>
+ <classpath>
+ <path refid="maven.test.classpath"/>
+ <pathelement location="${project.build.outputDirectory}"/>
+ <pathelement location="${fory.json.mr.classes}/17"/>
+ </classpath>
+ <compilerarg value="--release"/>
+ <compilerarg value="17"/>
+ <compilerarg value="-sourcepath"/>
+ <compilerarg value=""/>
+ </javac>
+ </target>
+ </configuration>
+ </execution>
<execution>
<id>inject-java17-feature</id>
<phase>package</phase>
@@ -425,6 +457,9 @@
<exclude name="module-info.class"/>
</fileset>
</copy>
+ <copy todir="${fory.json.jdk25.test.classes}" overwrite="true">
+ <fileset dir="${fory.json.mr.classes}/17" erroronmissingdir="false"/>
+ </copy>
<copy todir="${fory.json.jdk25.test.classes}" overwrite="true">
<fileset dir="${fory.json.mr.classes}/25">
<exclude name="module-info.class"/>
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java b/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java
index 619f89860..301d05b8c 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java
@@ -267,6 +267,10 @@ public final class ForyJsonBuilder {
*
* <p>The checker must be thread-safe because one {@link ForyJson} instance can be used
* concurrently.
+ *
+ * <p>For an empty {@code JsonSubTypes.value}, the checker filters exact classes from the inferred
+ * sealed closure. Rejecting every candidate is an error. A non-empty subtype table is an exact
+ * declaration and fails if the checker rejects an entry.
*/
public ForyJsonBuilder withTypeChecker(JsonTypeChecker typeChecker) {
this.typeChecker = typeChecker;
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/JsonTypeChecker.java b/java/fory-json/src/main/java/org/apache/fory/json/JsonTypeChecker.java
index 52cf1be37..ce80b36fc 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/JsonTypeChecker.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/JsonTypeChecker.java
@@ -37,6 +37,11 @@ import org.apache.fory.exception.InsecureException;
* <p>Decisions are shared by class name across the runtime's pooled states and cached up to a
* bounded number of distinct names. Once the cache is full, new names invoke the checker each time
* rather than growing untrusted state.
+ *
+ * <p>For an inferred sealed {@code JsonSubTypes} table, this checker may reject exact concrete
+ * candidates to narrow the statically authorized closure; rejecting every candidate fails schema
+ * construction. An explicit non-empty subtype table remains exact and fails if any entry is
+ * rejected. Fory's fixed disallow list validates the complete inferred closure before narrowing.
*/
@FunctionalInterface
public interface JsonTypeChecker {
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonSubTypes.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonSubTypes.java
index a150ce858..9ff92fede 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonSubTypes.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonSubTypes.java
@@ -26,7 +26,7 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
- * Declares the complete, finite subtype table for an interface or abstract base type.
+ * Declares a complete, finite subtype table for an interface or abstract base type.
*
* <p>JSON contains only the logical {@link Type#name() subtype name}; it never contains or selects
* a Java class name. Every entry is resolved from either a class literal or a static binary class
@@ -34,6 +34,12 @@ import java.lang.annotation.Target;
* used, including assignability, concreteness, duplicate-name, security, and type-checker rules.
* Runtime registration and open subtype discovery are intentionally unsupported.
*
+ * <p>When {@link #value()} is empty, Fory infers the concrete members of the base's sealed
+ * hierarchy. The user-selected base authorizes that static closure; JSON input still selects only a
+ * prevalidated logical name and never discovers a class. A non-empty value is an exact explicit
+ * subset. Applications that do not trust the complete sealed closure should declare that subset or
+ * configure {@code JsonTypeChecker}, which filters inferred exact candidates before publication.
+ *
* <p>{@link Inclusion#PROPERTY} is the default representation and writes an inline discriminator
* property as the first object member. {@link Inclusion#WRAPPER_OBJECT} writes one outer member
* whose name is the subtype name. {@link Inclusion#WRAPPER_ARRAY} writes the subtype name and value
@@ -48,8 +54,13 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface JsonSubTypes {
- /** Returns the complete closed subtype table. */
- Type[] value();
+ /**
+ * Returns the exact subtype table, or an empty array to infer the base's sealed hierarchy.
+ *
+ * <p>An explicit non-empty table is not extended by sealed inference. Inferred logical names are
+ * source simple names and therefore remain stable JSON schema names.
+ */
+ Type[] value() default {};
/**
* Returns the wire shape used to combine the logical subtype name with its value.
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/ClosedSubtypeCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/ClosedSubtypeCodec.java
index 107a31fc7..4a5fc4347 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/codec/ClosedSubtypeCodec.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/ClosedSubtypeCodec.java
@@ -48,6 +48,9 @@ import org.apache.fory.reflect.TypeRef;
* <p>Writing rejects fixed-schema discriminator collisions when branches are resolved, but never
* queries an Any Map. Runtime dynamic-key conflicts are owned by the application; probing here
* would invoke an Any getter twice and leak parent-specific policy into the child writer.
+ *
+ * <p>Input selects only a logical name from the already validated exact-class table. This codec
+ * never resolves a class name or expands the table while reading.
*/
@Internal
@SuppressWarnings("unchecked")
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/GeneratedJsonSubtypeTable.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/GeneratedJsonSubtypeTable.java
new file mode 100644
index 000000000..4b86b421e
--- /dev/null
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/GeneratedJsonSubtypeTable.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.fory.json.codec;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import org.apache.fory.annotation.Internal;
+
+/**
+ * Source-generated sealed-subtype schema metadata.
+ *
+ * <p>This table is trusted build-time schema input, not JSON-controlled class resolution. The
+ * shared registry still validates every class, logical name, and security policy before use.
+ */
+@Internal
+public interface GeneratedJsonSubtypeTable {
+ /** Returns the exact base described by this table. */
+ Class<?> type();
+
+ /** Returns the complete concrete sealed closure in canonical order. */
+ Class<?>[] subtypes();
+
+ /** Returns source simple names parallel to {@link #subtypes()}. */
+ String[] names();
+
+ /**
+ * Hands a Kotlin-source Mixin for a Java sealed root to Java annotation processing.
+ *
+ * <p>KSP cannot read Java permitted-subclass metadata. This source-only marker keeps Java sealed
+ * discovery in the annotation processor while naming the real Mixin that owns the generated pair
+ * table. It is trusted build metadata and is absent at runtime.
+ */
+ @Internal
+ @Retention(RetentionPolicy.SOURCE)
+ @Target(ElementType.TYPE)
+ @interface Generation {
+ /** Returns the qualified Kotlin Mixin name that requires Java closure generation. */
+ String mixin();
+ }
+}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/JsonSubTypesInfo.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/JsonSubTypesInfo.java
index 3963cecb1..f5ea6fe78 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/codec/JsonSubTypesInfo.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/JsonSubTypesInfo.java
@@ -81,7 +81,9 @@ public final class JsonSubTypesInfo {
}
}
- int classIndex(Class<?> type) {
+ /** Returns the exact class slot, or {@code -1} when the class is outside this table. */
+ @Internal
+ public int classIndex(Class<?> type) {
for (int i = 0; i < classes.length; i++) {
if (classes[i] == type) {
return i;
@@ -90,6 +92,18 @@ public final class JsonSubTypesInfo {
return -1;
}
+ /** Returns the number of exact branches in this table. */
+ @Internal
+ public int size() {
+ return classes.length;
+ }
+
+ /** Returns a snapshot of the exact accepted classes. */
+ @Internal
+ public Class<?>[] classes() {
+ return classes.clone();
+ }
+
private static byte[] join(byte[] left, byte[] right) {
byte[] result = new byte[left.length + right.length];
System.arraycopy(left, 0, result, 0, left.length);
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonNativeSubtypeRegistry.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonNativeSubtypeRegistry.java
new file mode 100644
index 000000000..c85d5ad56
--- /dev/null
+++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonNativeSubtypeRegistry.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.fory.json.resolver;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.fory.annotation.Internal;
+import org.apache.fory.platform.GraalvmSupport;
+
+/** Hosted-only owner that embeds complete inferred subtype schema tables in a native image. */
+@Internal
+public final class JsonNativeSubtypeRegistry {
+ private static final Map<Key, Table> TABLES = new HashMap<>();
+ private static boolean frozen;
+
+ private JsonNativeSubtypeRegistry() {}
+
+ static synchronized void publish(
+ Class<?> baseType, Class<?> mixinType, Class<?>[] classes, String[] names) {
+ if (!GraalvmSupport.isGraalBuildTime()) {
+ return;
+ }
+ if (frozen) {
+ throw new IllegalStateException("Native JSON subtype registry is frozen");
+ }
+ Key key = new Key(baseType, mixinType);
+ Table candidate = new Table(classes, names);
+ Table previous = TABLES.putIfAbsent(key, candidate);
+ if (previous != null && !previous.matches(classes, names)) {
+ throw new IllegalStateException("Conflicting inferred subtype tables for " + baseType);
+ }
+ }
+
+ static synchronized Table table(Class<?> baseType, Class<?> mixinType) {
+ return TABLES.get(new Key(baseType, mixinType));
+ }
+
+ /** Freezes hosted publication before the image heap is finalized. */
+ @Internal
+ public static synchronized void freeze() {
+ frozen = true;
+ }
+
+ static final class Table {
+ final Class<?>[] classes;
+ final String[] names;
+
+ private Table(Class<?>[] classes, String[] names) {
+ this.classes = classes.clone();
+ this.names = names.clone();
+ }
+
+ private boolean matches(Class<?>[] candidateClasses, String[] candidateNames) {
+ return Arrays.equals(classes, candidateClasses) && Arrays.equals(names, candidateNames);
+ }
+ }
+
+ private static final class Key {
+ private final Class<?> baseType;
+ private final Class<?> mixinType;
+
+ private Key(Class<?> baseType, Class<?> mixinType) {
+ this.baseType = baseType;
+ this.mixinType = mixinType;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof Key)) {
+ return false;
+ }
+ Key key = (Key) other;
+ return baseType == key.baseType && mixinType == key.mixinType;
+ }
+
+ @Override
+ public int hashCode() {
+ return 31 * System.identityHashCode(baseType) + System.identityHashCode(mixinType);
+ }
+ }
+}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonSharedRegistry.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonSharedRegistry.java
index e46d149c3..4c8b53ce4 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonSharedRegistry.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonSharedRegistry.java
@@ -107,9 +107,11 @@ import org.apache.fory.json.annotation.JsonSubTypes;
import org.apache.fory.json.annotation.JsonSubTypes.Inclusion;
import org.apache.fory.json.annotation.JsonType;
import org.apache.fory.json.codec.ArrayCodec;
+import org.apache.fory.json.codec.ClosedSubtypeCodec;
import org.apache.fory.json.codec.CodecUtils;
import org.apache.fory.json.codec.CollectionCodec;
import org.apache.fory.json.codec.GeneratedJsonCodec;
+import org.apache.fory.json.codec.GeneratedJsonSubtypeTable;
import org.apache.fory.json.codec.GuavaCodecs;
import org.apache.fory.json.codec.JsonSubTypesInfo;
import org.apache.fory.json.codec.JsonValueCodec;
@@ -537,6 +539,19 @@ public final class JsonSharedRegistry {
+ "; enable the Fory annotation processor and preserve its generated R8 rules");
}
+ private static ForyJsonException missingGeneratedSubtypeTable(Class<?> type, Class<?> mixinType) {
+ String name =
+ mixinType == null
+ ? generatedSubtypeTableBinaryName(type)
+ : generatedMixinSubtypeTableBinaryName(mixinType, type);
+ return new ForyJsonException(
+ "Missing generated JSON subtype table "
+ + name
+ + " for "
+ + type.getName()
+ + "; enable the Fory annotation processor and preserve its generated R8 rules");
+ }
+
private GeneratedJsonCodec<?> loadGeneratedCodec(Class<?> type, Class<?> mixinType) {
String generatedName =
mixinType == null
@@ -875,6 +890,10 @@ public final class JsonSharedRegistry {
return GeneratedClassNames.withSuffix(type.getName(), "_ForyJsonCodec");
}
+ private static String generatedSubtypeTableBinaryName(Class<?> type) {
+ return GeneratedClassNames.withSuffix(type.getName(), "_ForyJsonSubTypes");
+ }
+
private static String generatedMixinCodecBinaryName(Class<?> mixinType, Class<?> targetType) {
String sourceName = mixinType.getName();
int packageEnd = sourceName.lastIndexOf('.');
@@ -887,6 +906,13 @@ public final class JsonSharedRegistry {
+ "_ForyJsonCodec";
}
+ private static String generatedMixinSubtypeTableBinaryName(
+ Class<?> mixinType, Class<?> targetType) {
+ String codecName = generatedMixinCodecBinaryName(mixinType, targetType);
+ return codecName.substring(0, codecName.length() - "_ForyJsonCodec".length())
+ + "_ForyJsonSubTypes";
+ }
+
public JsonValueCodec<?> createCodec(
Class<?> rawType, TypeRef<?> typeRef, JsonTypeResolver localResolver) {
ResolvedCodec resolved = resolveCodec(rawType, typeRef, localResolver, null, false);
@@ -1001,6 +1027,10 @@ public final class JsonSharedRegistry {
if (resolved != null) {
return resolved;
}
+ if (inferredSubTypes(rawType)) {
+ return new ResolvedCodec(
+ new ClosedSubtypeCodec(rawType, subTypesInfo(rawType), typeRef), null);
+ }
if (Number.class.isAssignableFrom(rawType) || CharSequence.class.isAssignableFrom(rawType)) {
throw new ForyJsonException("Unsupported JSON type " + rawType);
}
@@ -1551,9 +1581,29 @@ public final class JsonSharedRegistry {
return cause == null ? new ForyJsonException(message) : new ForyJsonException(message, cause);
}
+ boolean hasSubTypes(Class<?> baseType) {
+ return effectiveSubTypes(baseType) != null;
+ }
+
+ boolean inferredSubTypes(Class<?> baseType) {
+ JsonSubTypes annotation = effectiveSubTypes(baseType);
+ return annotation != null && annotation.value().length == 0;
+ }
+
+ JsonSubTypesInfo explicitSubTypesInfo(Class<?> baseType) {
+ JsonSubTypes annotation = effectiveSubTypes(baseType);
+ return annotation == null || annotation.value().length == 0 ? null : subTypesInfo(baseType);
+ }
+
+ JsonSubTypesInfo cachedSubTypesInfo(Class<?> baseType) {
+ synchronized (subTypesCache) {
+ return subTypesCache.get(baseType);
+ }
+ }
+
JsonSubTypesInfo subTypesInfo(Class<?> baseType) {
try {
- JsonSubTypes annotation = annotation(baseType, baseType, JsonSubTypes.class);
+ JsonSubTypes annotation = effectiveSubTypes(baseType);
if (annotation == null) {
return null;
}
@@ -1562,7 +1612,37 @@ public final class JsonSharedRegistry {
if (cached != null) {
return cached;
}
- JsonSubTypesInfo resolved = buildSubTypesInfo(baseType, annotation);
+ JsonSubTypesInfo resolved;
+ if (annotation.value().length == 0) {
+ InferredSubtypes inferred = javaInferredSubtypes(baseType);
+ resolved =
+ buildInferredSubTypesInfo(baseType, annotation, inferred.classes, inferred.names);
+ } else {
+ resolved = buildExplicitSubTypesInfo(baseType, annotation);
+ }
+ subTypesCache.put(baseType, resolved);
+ return resolved;
+ }
+ } catch (ForyJsonException e) {
+ throw mixinSchemaFailure(baseType, e);
+ }
+ }
+
+ JsonSubTypesInfo inferredSubTypesInfo(
+ Class<?> baseType, Class<?>[] candidateClasses, String[] candidateNames) {
+ try {
+ JsonSubTypes annotation = effectiveSubTypes(baseType);
+ if (annotation == null || annotation.value().length != 0) {
+ throw new ForyJsonException(
+ "Inferred subtype metadata requires empty @JsonSubTypes on " + baseType.getName());
+ }
+ synchronized (subTypesCache) {
+ JsonSubTypesInfo cached = subTypesCache.get(baseType);
+ if (cached != null) {
+ return cached;
+ }
+ JsonSubTypesInfo resolved =
+ buildInferredSubTypesInfo(baseType, annotation, candidateClasses, candidateNames);
subTypesCache.put(baseType, resolved);
return resolved;
}
@@ -1571,7 +1651,11 @@ public final class JsonSharedRegistry {
}
}
- private JsonSubTypesInfo buildSubTypesInfo(Class<?> baseType, JsonSubTypes annotation) {
+ private JsonSubTypes effectiveSubTypes(Class<?> baseType) {
+ return annotation(baseType, baseType, JsonSubTypes.class);
+ }
+
+ private static void validateSubTypesDeclaration(Class<?> baseType, JsonSubTypes annotation) {
if (!baseType.isInterface() && !Modifier.isAbstract(baseType.getModifiers())) {
throw new ForyJsonException(
"@JsonSubTypes requires an interface or abstract type " + baseType);
@@ -1586,10 +1670,13 @@ public final class JsonSharedRegistry {
} else if (!property.isEmpty()) {
throw new ForyJsonException(inclusion + " @JsonSubTypes must not declare property");
}
+ }
+
+ private JsonSubTypesInfo buildExplicitSubTypesInfo(Class<?> baseType, JsonSubTypes annotation) {
+ validateSubTypesDeclaration(baseType, annotation);
+ Inclusion inclusion = annotation.inclusion();
+ String property = annotation.property();
JsonSubTypes.Type[] entries = annotation.value();
- if (entries.length == 0) {
- throw new ForyJsonException("@JsonSubTypes must declare at least one subtype");
- }
String[] names = new String[entries.length];
String[] classNames = new String[entries.length];
boolean hasStringEntry = false;
@@ -1659,6 +1746,208 @@ public final class JsonSharedRegistry {
return new JsonSubTypesInfo(inclusion, property, classes, names);
}
+ private JsonSubTypesInfo buildInferredSubTypesInfo(
+ Class<?> baseType,
+ JsonSubTypes annotation,
+ Class<?>[] candidateClasses,
+ String[] candidateNames) {
+ validateSubTypesDeclaration(baseType, annotation);
+ if (candidateClasses == null || candidateNames == null) {
+ throw new ForyJsonException("Missing inferred subtype metadata for " + baseType.getName());
+ }
+ if (candidateClasses.length == 0 || candidateClasses.length != candidateNames.length) {
+ throw new ForyJsonException("Invalid inferred subtype metadata for " + baseType.getName());
+ }
+ Class<?>[] classes = candidateClasses.clone();
+ String[] names = candidateNames.clone();
+ for (Class<?> subtype : classes) {
+ if (subtype == null) {
+ throw new ForyJsonException(
+ "Inferred subtype metadata contains null for " + baseType.getName());
+ }
+ }
+ sortSubtypes(classes, names);
+ Set<Class<?>> classIdentities =
+ Collections.newSetFromMap(new IdentityHashMap<Class<?>, Boolean>());
+ Set<String> binaryNames = new HashSet<>();
+ for (Class<?> subtype : classes) {
+ validateSubtype(baseType, subtype);
+ if (!classIdentities.add(subtype) || !binaryNames.add(subtype.getName())) {
+ throw new ForyJsonException("Duplicate closed JSON subtype " + subtype.getName());
+ }
+ // The selected static base authorizes its complete sealed closure. The fixed disallow list
+ // can invalidate that schema; the configurable checker below may only narrow exact entries.
+ DisallowedList.checkNotInDisallowedList(subtype.getName());
+ }
+ // Validate the complete static closure before configuration-level narrowing. A checker cannot
+ // turn an ambiguous schema into a valid table by hiding one duplicate or colliding name.
+ validateSubtypeNames(names);
+ JsonNativeSubtypeRegistry.publish(baseType, mixinType(baseType), classes, names);
+ JsonTypeChecker checker = typeChecker;
+ if (checker != null) {
+ int accepted = 0;
+ for (int i = 0; i < classes.length; i++) {
+ boolean allowed;
+ try {
+ allowed = checkType(classes[i].getName(), checker);
+ } catch (InsecureException ignored) {
+ allowed = false;
+ }
+ if (allowed) {
+ classes[accepted] = classes[i];
+ names[accepted] = names[i];
+ accepted++;
+ }
+ }
+ if (accepted == 0) {
+ throw new ForyJsonException(
+ "JsonTypeChecker rejected every inferred subtype of " + baseType.getName());
+ }
+ classes = java.util.Arrays.copyOf(classes, accepted);
+ names = java.util.Arrays.copyOf(names, accepted);
+ }
+ return new JsonSubTypesInfo(annotation.inclusion(), annotation.property(), classes, names);
+ }
+
+ private static void validateSubtype(Class<?> baseType, Class<?> subtype) {
+ if (subtype == null) {
+ throw new ForyJsonException(
+ "Inferred subtype metadata contains null for " + baseType.getName());
+ }
+ int modifiers = subtype.getModifiers();
+ if (subtype == Void.class
+ || subtype.isPrimitive()
+ || subtype.isArray()
+ || subtype.isInterface()
+ || Modifier.isAbstract(modifiers)
+ || !baseType.isAssignableFrom(subtype)) {
+ throw new ForyJsonException(
+ "Invalid closed JSON subtype " + subtype.getName() + " for " + baseType.getName());
+ }
+ }
+
+ private static void validateSubtypeNames(String[] names) {
+ Set<String> logicalNames = new HashSet<>();
+ Set<Long> logicalHashes = new HashSet<>();
+ for (String name : names) {
+ validateJsonName(name, "subtype");
+ if (!logicalNames.add(name)) {
+ throw new ForyJsonException("Invalid or duplicate JSON subtype name " + name);
+ }
+ long hash = org.apache.fory.json.meta.JsonFieldNameHash.hash(name);
+ if (!logicalHashes.add(Long.valueOf(hash))) {
+ throw new ForyJsonException("JSON subtype name hash collision for " + name);
+ }
+ }
+ }
+
+ private static void sortSubtypes(Class<?>[] classes, String[] names) {
+ for (int i = 1; i < classes.length; i++) {
+ Class<?> subtype = classes[i];
+ String name = names[i];
+ int j = i;
+ while (j > 0 && classes[j - 1].getName().compareTo(subtype.getName()) > 0) {
+ classes[j] = classes[j - 1];
+ names[j] = names[j - 1];
+ j--;
+ }
+ classes[j] = subtype;
+ names[j] = name;
+ }
+ }
+
+ private InferredSubtypes javaInferredSubtypes(Class<?> baseType) {
+ JsonNativeSubtypeRegistry.Table nativeTable =
+ JsonNativeSubtypeRegistry.table(baseType, mixinType(baseType));
+ if (nativeTable != null) {
+ return new InferredSubtypes(nativeTable.classes, nativeTable.names);
+ }
+ // Native Image runtime must consume the closure embedded during hosted analysis. Its Java
+ // sealed reflection metadata may be incomplete, so rediscovery here could silently change the
+ // authorized table instead of reporting a missing build-time schema root.
+ if (GraalvmSupport.isGraalRuntime()) {
+ throw new ForyJsonException(
+ "Missing embedded inferred subtype table for " + baseType.getName());
+ }
+ // A generated table owns source-level discriminator names after class-file obfuscation. Prefer
+ // it on every JVM; sealed reflection remains the unprocessed Java 17 fallback.
+ GeneratedJsonSubtypeTable table = loadGeneratedSubtypeTable(baseType);
+ if (table != null) {
+ return generatedSubtypes(baseType, table);
+ }
+ if (AndroidSupport.IS_ANDROID) {
+ throw missingGeneratedSubtypeTable(baseType, mixinType(baseType));
+ }
+ Class<?>[] classes = SealedClassSupport.subtypes(baseType);
+ if (classes != null) {
+ String[] names = new String[classes.length];
+ for (int i = 0; i < classes.length; i++) {
+ names[i] = classes[i].getSimpleName();
+ }
+ return new InferredSubtypes(classes, names);
+ }
+ throw new ForyJsonException(
+ "Empty @JsonSubTypes requires Java 17 sealed metadata or a generated subtype table for "
+ + baseType.getName());
+ }
+
+ private static InferredSubtypes generatedSubtypes(
+ Class<?> baseType, GeneratedJsonSubtypeTable table) {
+ try {
+ if (table.type() != baseType) {
+ throw new ForyJsonException(
+ "Generated JSON subtype table has the wrong base for " + baseType.getName());
+ }
+ return new InferredSubtypes(table.subtypes(), table.names());
+ } catch (RuntimeException | LinkageError e) {
+ if (e instanceof ForyJsonException) {
+ throw (ForyJsonException) e;
+ }
+ throw new ForyJsonException(
+ "Cannot read generated JSON subtype metadata for " + baseType.getName(), e);
+ }
+ }
+
+ private GeneratedJsonSubtypeTable loadGeneratedSubtypeTable(Class<?> baseType) {
+ Class<?> mixinType = mixinType(baseType);
+ String generatedName =
+ mixinType == null
+ ? generatedSubtypeTableBinaryName(baseType)
+ : generatedMixinSubtypeTableBinaryName(mixinType, baseType);
+ Class<?> generatedClass;
+ try {
+ generatedClass =
+ Class.forName(
+ generatedName,
+ false,
+ mixinType == null ? baseType.getClassLoader() : mixinType.getClassLoader());
+ } catch (ClassNotFoundException e) {
+ return null;
+ } catch (LinkageError e) {
+ throw new ForyJsonException("Cannot load generated JSON subtype table " + generatedName, e);
+ }
+ if (!GeneratedJsonSubtypeTable.class.isAssignableFrom(generatedClass)
+ || !Modifier.isPublic(generatedClass.getModifiers())) {
+ throw new ForyJsonException("Invalid generated JSON subtype table " + generatedName);
+ }
+ try {
+ return (GeneratedJsonSubtypeTable) generatedClass.getConstructor().newInstance();
+ } catch (ReflectiveOperationException e) {
+ throw new ForyJsonException(
+ "Cannot construct generated JSON subtype table " + generatedName, unwrap(e));
+ }
+ }
+
+ private static final class InferredSubtypes {
+ private final Class<?>[] classes;
+ private final String[] names;
+
+ private InferredSubtypes(Class<?>[] classes, String[] names) {
+ this.classes = classes;
+ this.names = names;
+ }
+ }
+
private void checkSecureName(String className) {
DisallowedList.checkNotInDisallowedList(className);
JsonTypeChecker checker = typeChecker;
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java
index d9e2c55e1..14357eb25 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java
@@ -188,7 +188,7 @@ public final class JsonTypeResolver {
// owner used to build an unwrapped parent.
return canonicalObjectCodec(typeInfo);
}
- if (customTypeInfo(rawType, rawType) != null || sharedRegistry.subTypesInfo(rawType) != null) {
+ if (customTypeInfo(rawType, rawType) != null || sharedRegistry.hasSubTypes(rawType)) {
return null;
}
JsonSharedRegistry.ResolvedCodec selected =
@@ -491,7 +491,7 @@ public final class JsonTypeResolver {
publishTypeInfo(key, typeInfo);
return typeInfo;
}
- JsonSubTypesInfo definition = sharedRegistry.subTypesInfo(rawType);
+ JsonSubTypesInfo definition = sharedRegistry.explicitSubTypesInfo(rawType);
if (definition != null) {
sharedRegistry.checkSecure(rawType);
ClosedSubtypeCodec codec = new ClosedSubtypeCodec(rawType, definition);
@@ -531,7 +531,7 @@ public final class JsonTypeResolver {
}
if (sharedRegistry.customCodec(rawType) != null
|| sharedRegistry.codecDeclaration(rawType) != null
- || sharedRegistry.subTypesInfo(rawType) != null) {
+ || sharedRegistry.hasSubTypes(rawType)) {
throw invalidCodecConfig(
rawType, "a child codec is hidden by the complete codec for the current value");
}
@@ -611,7 +611,7 @@ public final class JsonTypeResolver {
if (sharedRegistry.customCodec(rawType) != null
|| sharedRegistry.codecDeclaration(rawType) != null
|| sharedRegistry.valueDeclaration(rawType) != null
- || sharedRegistry.subTypesInfo(rawType) != null) {
+ || sharedRegistry.hasSubTypes(rawType)) {
throw invalidFormatConfig(rawType, "a complete representation hides its direct child");
}
sharedRegistry.checkSecure(rawType);
@@ -706,7 +706,7 @@ public final class JsonTypeResolver {
return;
}
Class<?> rawType = type.getRawType();
- if (!Modifier.isFinal(rawType.getModifiers()) && sharedRegistry.subTypesInfo(rawType) == null) {
+ if (!Modifier.isFinal(rawType.getModifiers()) && !sharedRegistry.hasSubTypes(rawType)) {
throw new ForyJsonException(
"Covariant JSON type must be final or declare effective @JsonSubTypes: " + type);
}
@@ -1033,6 +1033,80 @@ public final class JsonTypeResolver {
sharedRegistry.checkSecure(type);
}
+ /** Returns whether the exact type requests language-owned sealed subtype inference. */
+ @Internal
+ public boolean isInferredSubtype(Class<?> type) {
+ return sharedRegistry.inferredSubTypes(type);
+ }
+
+ /**
+ * Creates a dispatcher from an already published inferred table, or returns {@code null}.
+ *
+ * <p>This lets a language module avoid parsing hierarchy metadata again while keeping child
+ * codecs resolver-local.
+ */
+ @Internal
+ public JsonValueCodec<?> cachedInferredSubtypeCodec(
+ TypeRef<?> type, JsonCodecFactory childFactory) {
+ JsonSubTypesInfo definition = sharedRegistry.cachedSubTypesInfo(type.getRawType());
+ if (definition == null) {
+ JsonNativeSubtypeRegistry.Table table =
+ JsonNativeSubtypeRegistry.table(
+ type.getRawType(), sharedRegistry.mixinType(type.getRawType()));
+ if (table != null) {
+ definition =
+ sharedRegistry.inferredSubTypesInfo(type.getRawType(), table.classes, table.names);
+ }
+ }
+ return definition == null
+ ? null
+ : new ClosedSubtypeCodec(type.getRawType(), definition, type, childFactory);
+ }
+
+ /** Returns the accepted closed-subtype branches already resolved for hosted reachability. */
+ @Internal
+ public Class<?>[] resolvedSubtypeClasses(Class<?> type) {
+ JsonSubTypesInfo definition = sharedRegistry.cachedSubTypesInfo(type);
+ return definition == null ? new Class<?>[0] : definition.classes();
+ }
+
+ /**
+ * Validates and atomically publishes one language-produced sealed subtype table.
+ *
+ * <p>The producer supplies trusted static hierarchy metadata. Common validation applies fixed
+ * disallows and the configured checker before JSON input can select a logical name.
+ */
+ @Internal
+ public JsonValueCodec<?> createInferredSubtypeCodec(
+ TypeRef<?> type,
+ Class<?>[] classes,
+ String[] names,
+ JsonCodecFactory childFactory,
+ Object[] fixedInstances) {
+ JsonSubTypesInfo definition =
+ sharedRegistry.inferredSubTypesInfo(type.getRawType(), classes, names);
+ Object[] acceptedFixed = alignFixedInstances(definition, classes, fixedInstances);
+ return new ClosedSubtypeCodec(type.getRawType(), definition, type, childFactory, acceptedFixed);
+ }
+
+ private static Object[] alignFixedInstances(
+ JsonSubTypesInfo definition, Class<?>[] classes, Object[] fixedInstances) {
+ if (fixedInstances == null) {
+ return null;
+ }
+ if (classes == null || classes.length != fixedInstances.length) {
+ throw new IllegalArgumentException("Subtype fixed values do not match candidate classes");
+ }
+ Object[] accepted = new Object[definition.size()];
+ for (int i = 0; i < classes.length; i++) {
+ int index = definition.classIndex(classes[i]);
+ if (index >= 0) {
+ accepted[index] = fixedInstances[i];
+ }
+ }
+ return accepted;
+ }
+
/** Builds an unresolved object codec from language-module construction metadata. */
@Internal
public ObjectCodec<?> createObjectCodec(TypeRef<?> ownerType, JsonObjectModel objectModel) {
diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt b/java/fory-json/src/main/java/org/apache/fory/json/resolver/SealedClassSupport.java
similarity index 56%
copy from kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
copy to java/fory-json/src/main/java/org/apache/fory/json/resolver/SealedClassSupport.java
index 6867ca8fb..7bd8d77bb 100644
--- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
+++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/SealedClassSupport.java
@@ -17,30 +17,13 @@
* under the License.
*/
-package org.apache.fory.json.kotlin.ksp
+package org.apache.fory.json.resolver;
-import com.google.devtools.ksp.symbol.KSFile
+/** Java 8/Android base for Java sealed-hierarchy discovery. */
+final class SealedClassSupport {
+ private SealedClassSupport() {}
-internal enum class MemberKind {
- FIELD,
- METHOD,
+ static Class<?>[] subtypes(Class<?> baseType) {
+ return null;
+ }
}
-
-internal data class JvmMember(
- val kind: MemberKind,
- val ownerBinaryName: String,
- val name: String,
- val descriptor: String,
-)
-
-internal data class JsonModel(
- val targetBinaryName: String,
- val members: List<JvmMember>,
- val mixinBinaryName: String?,
- val originatingFiles: List<KSFile>,
- val retainedAnnotations: Set<String>,
- val annotationOwnerTypes: Set<String>,
- val retainedTypes: Set<String>,
- val codecTypes: Set<String>,
- val containerTypes: Set<String>,
-)
diff --git a/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java b/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java
index 40b5947b9..69f47379b 100644
--- a/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java
+++ b/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java
@@ -71,6 +71,7 @@ import org.apache.fory.json.meta.JsonFieldInfo;
import org.apache.fory.json.meta.JsonValidatorInfo;
import org.apache.fory.json.resolver.CodecRegistry.FactoryBinding;
import org.apache.fory.json.resolver.JsonGeneratedClassRegistry;
+import org.apache.fory.json.resolver.JsonNativeSubtypeRegistry;
import org.apache.fory.json.resolver.JsonSharedRegistry;
import org.apache.fory.json.resolver.JsonSharedRegistry.JsonMixinView;
import org.apache.fory.json.resolver.JsonTypeResolver;
@@ -95,6 +96,7 @@ final class ForyJsonGraalVMFeature implements Feature {
"value", "element", "content", "mapKey", "mapValue"
};
private static final String SCALA_ENUM_CLASS = "scala.reflect.Enum";
+ private static final String SCALA_PRODUCT_CLASS = "scala.Product";
private static final String[] SQL_TYPES = {
"java.sql.Date", "java.sql.Time", "java.sql.Timestamp"
};
@@ -107,7 +109,7 @@ final class ForyJsonGraalVMFeature implements Feature {
private final Map<Class<?>, Set<Class<?>>> reachableMixins = new LinkedHashMap<>();
private final Set<Class<?>> processedProviders = ConcurrentHashMap.newKeySet();
private final Set<Class<?>> processedFactoryModels = ConcurrentHashMap.newKeySet();
- private final Set<Class<?>> scalaDerivedModels = ConcurrentHashMap.newKeySet();
+ private final Set<Class<?>> scalaFactoryModels = ConcurrentHashMap.newKeySet();
private final Set<Class<?>> scalaEnumerationOwners = ConcurrentHashMap.newKeySet();
private final Set<Class<?>> processedCodecs = ConcurrentHashMap.newKeySet();
private final Set<Class<?>> processedContainers = ConcurrentHashMap.newKeySet();
@@ -143,12 +145,16 @@ final class ForyJsonGraalVMFeature implements Feature {
if (processedReachableTypes.add(type)) {
changed |= registerContainer(type);
changed |= registerDeclarations(type);
- changed |= registerScalaDerivedCodec(access, type);
- if (type.getDeclaredAnnotation(JsonType.class) != null) {
- changed |= registerModel(access, type);
- }
JsonMixin mixin = type.getDeclaredAnnotation(JsonMixin.class);
- if (mixin != null) {
+ if (mixin == null) {
+ boolean scalaModel = registerScalaModel(access, type);
+ changed |= scalaModel;
+ if ((type.getDeclaredAnnotation(JsonType.class) != null
+ || type.getDeclaredAnnotation(JsonSubTypes.class) != null)
+ && !scalaModel) {
+ changed |= registerModel(access, type);
+ }
+ } else {
changed |= registerMixin(access, type, mixin.target());
}
if (type.getDeclaredAnnotation(ForyJsonProvider.class) != null) {
@@ -168,22 +174,44 @@ final class ForyJsonGraalVMFeature implements Feature {
}
}
- private boolean registerScalaDerivedCodec(DuringAnalysisAccess access, Class<?> type) {
- boolean scalaEnum = false;
- for (Class<?> interfaceType : type.getInterfaces()) {
- if (interfaceType.getName().equals(SCALA_ENUM_CLASS)) {
- scalaEnum = true;
- break;
- }
+ private boolean registerScalaModel(DuringAnalysisAccess access, Class<?> type) {
+ boolean scalaEnum = implementsInterface(type, SCALA_ENUM_CLASS);
+ boolean scalaProduct = implementsInterface(type, SCALA_PRODUCT_CLASS);
+ boolean derivedSchema = scalaEnum;
+ if (!derivedSchema) {
+ JsonSubTypes subTypes = type.getDeclaredAnnotation(JsonSubTypes.class);
+ derivedSchema = subTypes != null && subTypes.value().length == 0;
}
- if (!scalaEnum) {
+ if (!derivedSchema
+ && !(scalaProduct && type.getDeclaredAnnotation(JsonType.class) != null)) {
return false;
}
Method method;
try {
method = type.getDeclaredMethod(SCALA_DERIVED_CODEC_METHOD);
} catch (NoSuchMethodException ignored) {
- return false;
+ JsonType jsonType = type.getDeclaredAnnotation(JsonType.class);
+ if (scalaEnum && jsonType != null) {
+ try {
+ method = type.getMethod("values");
+ } catch (NoSuchMethodException missingValues) {
+ return false;
+ }
+ int modifiers = method.getModifiers();
+ if (!Modifier.isPublic(modifiers)
+ || !Modifier.isStatic(modifiers)
+ || method.getParameterCount() != 0
+ || !method.getReturnType().isArray()
+ || method.getReturnType().getComponentType() != type) {
+ return false;
+ }
+ RuntimeReflection.register(method);
+ } else if (!scalaProduct || jsonType == null) {
+ return false;
+ }
+ scalaFactoryModels.add(type);
+ registerFactoryModel(access, type);
+ return true;
}
int modifiers = method.getModifiers();
if (!Modifier.isPublic(modifiers)
@@ -193,8 +221,22 @@ final class ForyJsonGraalVMFeature implements Feature {
return false;
}
RuntimeReflection.register(method);
- scalaDerivedModels.add(type);
+ JsonCodecFactory factory;
+ try {
+ factory = (JsonCodecFactory) method.invoke(null);
+ } catch (ReflectiveOperationException e) {
+ throw new IllegalStateException(
+ "Cannot load derived Scala JSON codec for " + type.getName(), e);
+ }
+ if (factory == null) {
+ throw new IllegalStateException(
+ "Derived Scala JSON codec is null for " + type.getName());
+ }
+ scalaFactoryModels.add(type);
registerFactoryModel(access, type);
+ for (Class<?> runtimeType : factory.handledRuntimeClasses()) {
+ registerFactoryModel(access, runtimeType);
+ }
return true;
}
@@ -331,7 +373,7 @@ final class ForyJsonGraalVMFeature implements Feature {
LinkedHashSet<Class<?>> selectedModels = new LinkedHashSet<>(processedModels);
selectedModels.addAll(configuration.factoryModels);
if (configuration.scalaJsonCodecs) {
- selectedModels.addAll(scalaDerivedModels);
+ selectedModels.addAll(scalaFactoryModels);
}
for (Map.Entry<Class<?>, Set<Class<?>>> mixin : reachableMixins.entrySet()) {
if (mixin.getValue().contains(configuration.mixins.get(mixin.getKey()))) {
@@ -362,6 +404,13 @@ final class ForyJsonGraalVMFeature implements Feature {
for (ObjectCodec<?> objectModel : objectModels) {
registerObjectModel(access, objectModel);
}
+ boolean scalaModel = scalaFactoryModels.contains(model);
+ for (Class<?> subtype : configuration.resolver.resolvedSubtypeClasses(model)) {
+ changed |=
+ scalaModel
+ ? registerFactoryModel(access, subtype)
+ : registerModel(access, subtype);
+ }
generated = true;
changed = true;
}
@@ -644,6 +693,7 @@ final class ForyJsonGraalVMFeature implements Feature {
@Override
public void afterAnalysis(AfterAnalysisAccess access) {
+ JsonNativeSubtypeRegistry.freeze();
JsonGeneratedClassRegistry.freeze();
JsonCodegen.resetGeneratedClassCache();
}
@@ -1091,6 +1141,17 @@ final class ForyJsonGraalVMFeature implements Feature {
return null;
}
+ private static boolean implementsInterface(Class<?> type, String interfaceName) {
+ for (Class<?> interfaceType : type.getInterfaces()) {
+ if (interfaceType.getName().equals(interfaceName)
+ || implementsInterface(interfaceType, interfaceName)) {
+ return true;
+ }
+ }
+ Class<?> superType = type.getSuperclass();
+ return superType != null && implementsInterface(superType, interfaceName);
+ }
+
private static final class HostedConfiguration {
private final JsonSharedRegistry registry;
private final JsonTypeResolver resolver;
diff --git a/java/fory-json/src/main/java17/org/apache/fory/json/resolver/SealedClassSupport.java b/java/fory-json/src/main/java17/org/apache/fory/json/resolver/SealedClassSupport.java
new file mode 100644
index 000000000..c61927ea4
--- /dev/null
+++ b/java/fory-json/src/main/java17/org/apache/fory/json/resolver/SealedClassSupport.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.fory.json.resolver;
+
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.Set;
+import org.apache.fory.json.ForyJsonException;
+
+/** Java 17 sealed-hierarchy discovery backed only by class-file schema metadata. */
+final class SealedClassSupport {
+ private SealedClassSupport() {}
+
+ static Class<?>[] subtypes(Class<?> baseType) {
+ if (!baseType.isSealed()) {
+ throw new ForyJsonException(
+ "Empty @JsonSubTypes requires a sealed Java type " + baseType.getName());
+ }
+ // PermittedSubclasses is trusted static schema metadata. JSON input never influences this
+ // traversal and later selects only a logical name from the validated finite result.
+ ArrayList<Class<?>> result = new ArrayList<>();
+ Set<Class<?>> visited = Collections.newSetFromMap(new IdentityHashMap<Class<?>, Boolean>());
+ collect(baseType, result, visited);
+ return result.toArray(new Class<?>[0]);
+ }
+
+ private static void collect(
+ Class<?> sealedType, ArrayList<Class<?>> result, Set<Class<?>> visited) {
+ for (Class<?> subtype : sealedType.getPermittedSubclasses()) {
+ if (!visited.add(subtype)) {
+ continue;
+ }
+ int modifiers = subtype.getModifiers();
+ boolean concrete = !subtype.isInterface() && !Modifier.isAbstract(modifiers);
+ if (concrete) {
+ result.add(subtype);
+ }
+ if (subtype.isSealed()) {
+ collect(subtype, result, visited);
+ } else if (!concrete) {
+ throw new ForyJsonException(
+ "Sealed JSON hierarchy has an open abstract branch " + subtype.getName());
+ }
+ }
+ }
+}
diff --git a/java/fory-json/src/test/java17/org/apache/fory/json/JsonSealedSubTypesTest.java b/java/fory-json/src/test/java17/org/apache/fory/json/JsonSealedSubTypesTest.java
new file mode 100644
index 000000000..011304385
--- /dev/null
+++ b/java/fory-json/src/test/java17/org/apache/fory/json/JsonSealedSubTypesTest.java
@@ -0,0 +1,236 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.fory.json;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertThrows;
+
+import java.util.Arrays;
+import java.util.List;
+import org.apache.fory.exception.InsecureException;
+import org.apache.fory.json.annotation.JsonSubTypes;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class JsonSealedSubTypesTest {
+ @DataProvider
+ public static Object[][] codegen() {
+ return new Object[][] {{Boolean.FALSE}, {Boolean.TRUE}};
+ }
+
+ @Test(dataProvider = "codegen")
+ public void inferredClosure(boolean codegen) {
+ ForyJson json =
+ ForyJson.builder().withCodegen(codegen).withAsyncCompilation(false).build();
+ List<InferredShape> values =
+ Arrays.asList(
+ new Circle(2),
+ new Leaf(3),
+ new OpenBranch(4),
+ new ConcreteSealed(5),
+ new ConcreteLeaf(6));
+ String[] names = {"Circle", "Leaf", "OpenBranch", "ConcreteSealed", "ConcreteLeaf"};
+ for (int i = 0; i < values.size(); i++) {
+ InferredShape value = values.get(i);
+ String text = json.toJson(value, InferredShape.class);
+ assertEquals(text.contains("\"kind\":\"" + names[i] + "\""), true, text);
+ InferredShape decoded = json.fromJson(text, InferredShape.class);
+ assertEquals(decoded.getClass(), value.getClass());
+ assertEquals(decoded.value(), value.value());
+ }
+ assertThrows(
+ ForyJsonException.class,
+ () -> json.toJson(new OpenDescendant(7), InferredShape.class));
+ }
+
+ @Test(dataProvider = "codegen")
+ public void generatedTablePrecedesReflection(boolean codegen) {
+ ForyJson json =
+ ForyJson.builder().withCodegen(codegen).withAsyncCompilation(false).build();
+ String text = json.toJson(new GeneratedLeaf(8), GeneratedShape.class);
+ assertEquals(text, "{\"kind\":\"StableLeaf\",\"value\":8}");
+ assertEquals(json.fromJson(text, GeneratedShape.class).getClass(), GeneratedLeaf.class);
+ }
+
+ @Test
+ public void checkerNarrowsExactBranches() {
+ ForyJson json =
+ ForyJson.builder()
+ .withCodegen(false)
+ .withTypeChecker(
+ (name, context) -> {
+ if (name.equals(ConcreteSealed.class.getName())) {
+ throw new InsecureException("rejected branch");
+ }
+ return true;
+ })
+ .build();
+ assertThrows(
+ ForyJsonException.class,
+ () -> json.toJson(new ConcreteSealed(1), InferredShape.class));
+ ConcreteLeaf leaf =
+ (ConcreteLeaf)
+ json.fromJson("{\"kind\":\"ConcreteLeaf\",\"value\":2}", InferredShape.class);
+ assertEquals(leaf.value, 2);
+ }
+
+ @Test
+ public void rejectEmptyEffectiveClosure() {
+ ForyJson json =
+ ForyJson.builder()
+ .withCodegen(false)
+ .withTypeChecker(
+ (name, context) -> name.equals(InferredShape.class.getName()))
+ .build();
+ assertThrows(ForyJsonException.class, () -> json.fromJson("{}", InferredShape.class));
+ }
+
+ @Test
+ public void rejectOpenAbstractBranch() {
+ ForyJson json = ForyJson.builder().withCodegen(false).build();
+ assertThrows(ForyJsonException.class, () -> json.fromJson("{}", InvalidShape.class));
+ }
+
+ @Test
+ public void validateFullClosureBeforeChecker() {
+ ForyJson json =
+ ForyJson.builder()
+ .withCodegen(false)
+ .withTypeChecker(
+ (name, context) ->
+ name.equals(DuplicateNames.class.getName())
+ || name.equals(LeftBranch.Entry.class.getName()))
+ .build();
+ assertThrows(ForyJsonException.class, () -> json.fromJson("{}", DuplicateNames.class));
+ }
+
+ @JsonSubTypes(property = "kind")
+ public sealed interface InferredShape
+ permits Circle, Branch, OpenBranch, ConcreteSealed {
+ int value();
+ }
+
+ public static final class Circle implements InferredShape {
+ public int value;
+
+ public Circle() {}
+
+ Circle(int value) {
+ this.value = value;
+ }
+
+ @Override
+ public int value() {
+ return value;
+ }
+ }
+
+ public abstract static sealed class Branch implements InferredShape permits Leaf {}
+
+ public static final class Leaf extends Branch {
+ public int value;
+
+ public Leaf() {}
+
+ Leaf(int value) {
+ this.value = value;
+ }
+
+ @Override
+ public int value() {
+ return value;
+ }
+ }
+
+ public static non-sealed class OpenBranch implements InferredShape {
+ public int value;
+
+ public OpenBranch() {}
+
+ OpenBranch(int value) {
+ this.value = value;
+ }
+
+ @Override
+ public int value() {
+ return value;
+ }
+ }
+
+ public static final class OpenDescendant extends OpenBranch {
+ public OpenDescendant() {}
+
+ OpenDescendant(int value) {
+ super(value);
+ }
+ }
+
+ public static sealed class ConcreteSealed implements InferredShape permits ConcreteLeaf {
+ public int value;
+
+ public ConcreteSealed() {}
+
+ ConcreteSealed(int value) {
+ this.value = value;
+ }
+
+ @Override
+ public int value() {
+ return value;
+ }
+ }
+
+ public static final class ConcreteLeaf extends ConcreteSealed {
+ public ConcreteLeaf() {}
+
+ ConcreteLeaf(int value) {
+ super(value);
+ }
+ }
+
+ @JsonSubTypes(property = "kind")
+ public sealed interface GeneratedShape permits GeneratedLeaf {}
+
+ public static final class GeneratedLeaf implements GeneratedShape {
+ public int value;
+
+ public GeneratedLeaf() {}
+
+ GeneratedLeaf(int value) {
+ this.value = value;
+ }
+ }
+
+ @JsonSubTypes(property = "kind")
+ public sealed interface InvalidShape permits OpenAbstractBranch {}
+
+ public abstract static non-sealed class OpenAbstractBranch implements InvalidShape {}
+
+ @JsonSubTypes(property = "kind")
+ public sealed interface DuplicateNames permits LeftBranch, RightBranch {}
+
+ public sealed interface LeftBranch extends DuplicateNames permits LeftBranch.Entry {
+ public final class Entry implements LeftBranch {}
+ }
+
+ public sealed interface RightBranch extends DuplicateNames permits RightBranch.Entry {
+ public final class Entry implements RightBranch {}
+ }
+}
diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt b/java/fory-json/src/test/java17/org/apache/fory/json/JsonSealedSubTypesTest_d_GeneratedShape_ForyJsonSubTypes.java
similarity index 56%
copy from kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
copy to java/fory-json/src/test/java17/org/apache/fory/json/JsonSealedSubTypesTest_d_GeneratedShape_ForyJsonSubTypes.java
index 6867ca8fb..b538fa106 100644
--- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
+++ b/java/fory-json/src/test/java17/org/apache/fory/json/JsonSealedSubTypesTest_d_GeneratedShape_ForyJsonSubTypes.java
@@ -17,30 +17,25 @@
* under the License.
*/
-package org.apache.fory.json.kotlin.ksp
+package org.apache.fory.json;
-import com.google.devtools.ksp.symbol.KSFile
+import org.apache.fory.json.codec.GeneratedJsonSubtypeTable;
-internal enum class MemberKind {
- FIELD,
- METHOD,
-}
+/** Simulates annotation-processor metadata whose source name differs from reflection metadata. */
+public final class JsonSealedSubTypesTest_d_GeneratedShape_ForyJsonSubTypes
+ implements GeneratedJsonSubtypeTable {
+ @Override
+ public Class<?> type() {
+ return JsonSealedSubTypesTest.GeneratedShape.class;
+ }
-internal data class JvmMember(
- val kind: MemberKind,
- val ownerBinaryName: String,
- val name: String,
- val descriptor: String,
-)
+ @Override
+ public Class<?>[] subtypes() {
+ return new Class<?>[] {JsonSealedSubTypesTest.GeneratedLeaf.class};
+ }
-internal data class JsonModel(
- val targetBinaryName: String,
- val members: List<JvmMember>,
- val mixinBinaryName: String?,
- val originatingFiles: List<KSFile>,
- val retainedAnnotations: Set<String>,
- val annotationOwnerTypes: Set<String>,
- val retainedTypes: Set<String>,
- val codecTypes: Set<String>,
- val containerTypes: Set<String>,
-)
+ @Override
+ public String[] names() {
+ return new String[] {"StableLeaf"};
+ }
+}
diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt
index d8add2315..dbcfc015e 100644
--- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt
+++ b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt
@@ -39,14 +39,19 @@ internal class ForyJsonKotlinSymbolProcessor(environment: SymbolProcessorEnviron
override fun process(resolver: Resolver): List<KSAnnotated> {
val deferred = ArrayList<KSAnnotated>()
val modelBuilder = KspModelBuilder(resolver, logger)
- for (symbol in resolver.getSymbolsWithAnnotation(JSON_TYPE)) {
+ val directSymbols =
+ sequenceOf(JSON_TYPE, JSON_SUB_TYPES).flatMap(resolver::getSymbolsWithAnnotation).distinct()
+ for (symbol in directSymbols) {
if (!symbol.validate()) {
deferred += symbol
continue
}
val declaration = symbol as? KSClassDeclaration
if (declaration == null) {
- logger.error("@JsonType can only be used on classes, interfaces, and objects", symbol)
+ logger.error(
+ "@JsonType and @JsonSubTypes can only be used on classes, interfaces, and objects",
+ symbol,
+ )
continue
}
val model = modelBuilder.direct(declaration) ?: continue
@@ -63,6 +68,12 @@ internal class ForyJsonKotlinSymbolProcessor(environment: SymbolProcessorEnviron
logger.error("@JsonMixin can only be used on classes and interfaces", symbol)
continue
}
+ val generation = modelBuilder.javaSubtypeGeneration(declaration)
+ if (generation != null) {
+ val key = "${generation.packageName}.${generation.simpleName}"
+ if (generatedRequests.add(key)) write(generation)
+ continue
+ }
val model = modelBuilder.mixin(declaration) ?: continue
if (!generatedRequests.add(R8RulesWriter.resourcePath(model))) continue
write(model)
@@ -72,10 +83,22 @@ internal class ForyJsonKotlinSymbolProcessor(environment: SymbolProcessorEnviron
private fun write(model: JsonModel) {
val dependencies =
- Dependencies(aggregating = false, sources = model.originatingFiles.toTypedArray())
+ Dependencies(aggregating = model.aggregating, sources = model.originatingFiles.toTypedArray())
codeGenerator.createNewFileByPath(dependencies, R8RulesWriter.resourcePath(model), "").use {
output ->
output.write(R8RulesWriter.write(model).toByteArray(StandardCharsets.UTF_8))
}
}
+
+ private fun write(generation: JavaSubtypeGeneration) {
+ val dependencies =
+ Dependencies(aggregating = true, sources = generation.originatingFiles.toTypedArray())
+ codeGenerator
+ .createNewFile(dependencies, generation.packageName, generation.simpleName, "java")
+ .use { output ->
+ output.write(
+ JavaSubtypeGenerationWriter.write(generation).toByteArray(StandardCharsets.UTF_8)
+ )
+ }
+ }
}
diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/JavaSubtypeGenerationWriter.kt b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/JavaSubtypeGenerationWriter.kt
new file mode 100644
index 000000000..e7f636e39
--- /dev/null
+++ b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/JavaSubtypeGenerationWriter.kt
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.fory.json.kotlin.ksp
+
+/** Hands a Kotlin-source Mixin to the Java sealed-hierarchy metadata owner. */
+internal object JavaSubtypeGenerationWriter {
+ fun write(generation: JavaSubtypeGeneration): String =
+ buildString(512) {
+ if (generation.packageName.isNotEmpty()) append("package ${generation.packageName};\n\n")
+ append("@org.apache.fory.json.codec.GeneratedJsonSubtypeTable.Generation(")
+ append("mixin = \"")
+ generation.mixinSourceName.forEach { character ->
+ when (character) {
+ '\\' -> append("\\\\")
+ '"' -> append("\\\"")
+ '\b' -> append("\\b")
+ '\u000C' -> append("\\f")
+ '\n' -> append("\\n")
+ '\r' -> append("\\r")
+ '\t' -> append("\\t")
+ else -> append(character)
+ }
+ }
+ append("\")\n")
+ append("final class ${generation.simpleName} {}\n")
+ }
+}
diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt
index 5496b1656..6e89bb7c7 100644
--- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt
+++ b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt
@@ -44,7 +44,7 @@ import com.google.devtools.ksp.symbol.Origin
internal const val JSON_TYPE: String = "org.apache.fory.json.annotation.JsonType"
internal const val JSON_MIXIN: String = "org.apache.fory.json.annotation.JsonMixin"
-private const val JSON_SUB_TYPES = "org.apache.fory.json.annotation.JsonSubTypes"
+internal const val JSON_SUB_TYPES: String = "org.apache.fory.json.annotation.JsonSubTypes"
private const val JSON_SUB_TYPE = "org.apache.fory.json.annotation.JsonSubTypes.Type"
private const val JSON_CODEC = "org.apache.fory.json.annotation.JsonCodec"
private const val JSON_BASE64 = "org.apache.fory.json.annotation.JsonBase64"
@@ -78,35 +78,233 @@ internal class KspModelBuilder(
fun direct(target: KSClassDeclaration): JsonModel? {
if (target.origin != Origin.KOTLIN || target.containingFile == null) return null
if (hasAnnotation(target, JSON_MIXIN)) return null
- return kotlinModel(target, null)
+ val typeCodec = hasCompleteTypeCodec(target, null)
+ val model = if (typeCodec) typeCodecModel(target, null) else kotlinModel(target, null)
+ return model?.let {
+ if (emptySubTypes(target, null) && !typeCodec) sealedModel(target, null, it) else it
+ }
+ }
+
+ fun javaSubtypeGeneration(source: KSClassDeclaration): JavaSubtypeGeneration? {
+ if (source.origin != Origin.KOTLIN || source.containingFile == null) return null
+ val target = mixinTarget(source) ?: return null
+ if (isKotlin(target.origin) || !emptySubTypes(target, source)) return null
+ if (hasCompleteTypeCodec(target, source)) return null
+ val mixinBinaryName = binaryName(source) ?: return fail(source, "@JsonMixin must be named")
+ val mixinSourceName =
+ source.qualifiedName?.asString() ?: return fail(source, "@JsonMixin must be named")
+ return JavaSubtypeGeneration(
+ packageName = source.packageName.asString(),
+ simpleName =
+ escapeGeneratedName(mixinBinaryName.substringAfterLast('.')) + "_ForyJsonSubtypeGeneration",
+ mixinSourceName = mixinSourceName,
+ originatingFiles = originatingFiles(target, source),
+ )
}
fun mixin(source: KSClassDeclaration): JsonModel? {
if (source.containingFile == null || source.origin !in SOURCE_ORIGINS) return null
val target = mixinTarget(source) ?: return null
if (source.origin == Origin.JAVA && !isKotlin(target.origin)) return null
- return if (isKotlin(target.origin)) {
- kotlinModel(target, source)
- } else {
- javaModel(target, source)
+ val typeCodec = hasCompleteTypeCodec(target, source)
+ val model =
+ if (typeCodec) typeCodecModel(target, source)
+ else if (isKotlin(target.origin)) kotlinModel(target, source) else javaModel(target, source)
+ return model?.let {
+ if (isKotlin(target.origin) && emptySubTypes(target, source) && !typeCodec) {
+ sealedModel(target, source, it)
+ } else {
+ it
+ }
+ }
+ }
+
+ private fun emptySubTypes(
+ target: KSClassDeclaration,
+ mixin: KSClassDeclaration?,
+ ): Boolean {
+ val annotation = effectiveAnnotation(target, mixin, JSON_SUB_TYPES) ?: return false
+ val value = annotation.arguments.firstOrNull { it.name?.asString() == "value" }?.value
+ return value == null || value is Iterable<*> && value.none()
+ }
+
+ private fun hasCompleteTypeCodec(
+ target: KSClassDeclaration,
+ mixin: KSClassDeclaration?,
+ ): Boolean {
+ if (effectiveAnnotation(target, mixin, JSON_CODEC)?.let(::selectsValueCodec) == true) {
+ return true
+ }
+ if (mixin != null && removesAnnotation(mixin, JSON_CODEC)) return false
+ val candidates =
+ target
+ .getAllSuperTypes()
+ .mapNotNull { actual(it.declaration) as? KSClassDeclaration }
+ .distinctBy(::binaryName)
+ .mapNotNull { declaration ->
+ declaration.annotations
+ .firstOrNull { annotationName(it) == JSON_CODEC }
+ ?.let { declaration to it }
+ }
+ .toList()
+ return candidates.any { candidate ->
+ val owner = candidate.first
+ val dominated =
+ candidates.any { other ->
+ other.first != owner &&
+ owner.asStarProjectedType().isAssignableFrom(other.first.asStarProjectedType())
+ }
+ !dominated && selectsValueCodec(candidate.second)
+ }
+ }
+
+ private fun selectsValueCodec(annotation: KSAnnotation): Boolean {
+ val value =
+ annotation.arguments.firstOrNull { it.name?.asString() == "value" }?.value as? KSType
+ ?: return false
+ val declaration = actual(value.declaration) as? KSClassDeclaration ?: return false
+ return declaration.qualifiedName?.asString() !in CODEC_SENTINELS
+ }
+
+ private fun typeCodecModel(
+ target: KSClassDeclaration,
+ mixin: KSClassDeclaration?,
+ ): JsonModel? {
+ val targetName = binaryName(target) ?: return fail(target, "JSON target must be named")
+ val retention = Retention()
+ val origins = ArrayList(listOfNotNull(target.containingFile, mixin?.containingFile))
+ effectiveAnnotation(target, mixin, JSON_CODEC)?.let { annotation ->
+ retention.annotations += JSON_CODEC
+ collectCodecAnnotation(annotation, retention.codecs)
+ }
+ if (mixin == null || !removesAnnotation(mixin, JSON_CODEC)) {
+ target.getAllSuperTypes().forEach { supertype ->
+ val owner = actual(supertype.declaration) as? KSClassDeclaration ?: return@forEach
+ owner.annotations
+ .firstOrNull { annotationName(it) == JSON_CODEC }
+ ?.let { annotation ->
+ retention.annotations += JSON_CODEC
+ collectCodecAnnotation(annotation, retention.codecs)
+ binaryName(owner)?.let(retention.annotationOwners::add)
+ owner.containingFile?.let(origins::add)
+ }
+ }
+ }
+ if (mixin != null) {
+ retention.annotations += JSON_MIXIN
+ if (hasAnnotation(mixin, JSON_MIXIN_REMOVE)) retention.annotations += JSON_MIXIN_REMOVE
+ }
+ return JsonModel(
+ targetBinaryName = targetName,
+ members = emptyList(),
+ mixinBinaryName = mixin?.let(::binaryName),
+ originatingFiles = origins.distinct(),
+ retainedAnnotations = retention.annotations,
+ annotationOwnerTypes = retention.annotationOwners,
+ retainedTypes = emptySet(),
+ codecTypes = retention.codecs,
+ containerTypes = emptySet(),
+ )
+ }
+
+ private fun escapeGeneratedName(value: String): String {
+ val result = java.lang.StringBuilder(value.length + 32)
+ var index = 0
+ while (index < value.length) {
+ val codePoint = value.codePointAt(index)
+ when {
+ codePoint == '$'.code -> result.append("_d_")
+ codePoint == '_'.code -> result.append("_u_")
+ Character.isJavaIdentifierPart(codePoint) -> result.appendCodePoint(codePoint)
+ else -> result.append("_x").append(Integer.toHexString(codePoint)).append('_')
+ }
+ index += Character.charCount(codePoint)
}
+ return result.toString()
+ }
+
+ private fun sealedModel(
+ target: KSClassDeclaration,
+ mixin: KSClassDeclaration?,
+ root: JsonModel,
+ ): JsonModel? {
+ if (Modifier.SEALED !in target.modifiers) {
+ return fail(target, "Empty @JsonSubTypes requires a sealed type")
+ }
+ if (target.classKind != ClassKind.INTERFACE && Modifier.ABSTRACT !in target.modifiers) {
+ return fail(target, "@JsonSubTypes requires an interface or abstract base type")
+ }
+ // KSP symbols are trusted build-time schema metadata. Retaining the exact closure keeps
+ // runtime Kotlin metadata discovery finite and stable after R8/ProGuard.
+ val declarations = ArrayList<KSClassDeclaration>()
+ val closure = ArrayList<KSClassDeclaration>()
+ val retained = linkedSetOf<String>()
+ val visited = linkedSetOf<String>()
+ fun collect(sealedType: KSClassDeclaration): Boolean {
+ for (subtype in sealedType.getSealedSubclasses()) {
+ val binary = binaryName(subtype) ?: return false
+ if (!visited.add(binary)) continue
+ closure += subtype
+ retained += binary
+ val concrete =
+ subtype.classKind != ClassKind.INTERFACE && Modifier.ABSTRACT !in subtype.modifiers
+ if (concrete) declarations += subtype
+ if (Modifier.SEALED in subtype.modifiers) {
+ if (!collect(subtype)) return false
+ } else if (!concrete) {
+ fail<Any>(subtype, "Sealed JSON hierarchy has an open abstract branch")
+ return false
+ }
+ }
+ return true
+ }
+ if (!collect(target)) return null
+ if (declarations.isEmpty()) {
+ fail<Any>(target, "Sealed JSON hierarchy has no concrete subtype")
+ return null
+ }
+ declarations.sortBy { binaryName(it) }
+ val models = ArrayList<JsonModel>(declarations.size + 1)
+ models += root
+ for (declaration in declarations) {
+ models +=
+ if (isKotlin(declaration.origin)) kotlinModel(declaration, null) ?: return null
+ else javaModel(declaration, null) ?: return null
+ }
+ val closureFiles = closure.mapNotNull(KSClassDeclaration::containingFile)
+ return JsonModel(
+ targetBinaryName = root.targetBinaryName,
+ members = models.flatMap(JsonModel::members).distinct(),
+ mixinBinaryName = root.mixinBinaryName,
+ originatingFiles =
+ (models.flatMap(JsonModel::originatingFiles) +
+ closureFiles +
+ listOfNotNull(target.containingFile, mixin?.containingFile))
+ .distinct(),
+ retainedAnnotations = models.flatMap(JsonModel::retainedAnnotations).toSet(),
+ annotationOwnerTypes = models.flatMap(JsonModel::annotationOwnerTypes).toSet(),
+ retainedTypes = models.flatMap(JsonModel::retainedTypes).toSet() + retained,
+ codecTypes = models.flatMap(JsonModel::codecTypes).toSet(),
+ containerTypes = models.flatMap(JsonModel::containerTypes).toSet(),
+ aggregating = true,
+ )
}
private fun javaModel(
target: KSClassDeclaration,
- mixin: KSClassDeclaration,
+ mixin: KSClassDeclaration?,
): JsonModel? {
- val targetName = binaryName(target) ?: return fail(target, "@JsonMixin target must be named")
+ val targetName = binaryName(target) ?: return fail(target, "JSON target must be named")
val members =
javaMembers(target, mixin) +
- mixinMembers(mixin) +
+ (mixin?.let(::mixinMembers) ?: emptyList()) +
listOfNotNull(javaAnySetter(target, mixin), javaCreator(target, mixin)) +
validators(target, mixin)
val retention = retention(target, mixin)
return JsonModel(
targetBinaryName = targetName,
members = members,
- mixinBinaryName = binaryName(mixin),
+ mixinBinaryName = mixin?.let(::binaryName),
originatingFiles = originatingFiles(target, mixin),
retainedAnnotations = retention.annotations,
annotationOwnerTypes = retention.annotationOwners,
@@ -428,7 +626,7 @@ internal class KspModelBuilder(
private fun javaMembers(
target: KSClassDeclaration,
- mixin: KSClassDeclaration,
+ mixin: KSClassDeclaration?,
): List<JvmMember> {
val result = linkedMapOf<String, JvmMember>()
for (property in target.getAllProperties()) {
@@ -500,7 +698,7 @@ internal class KspModelBuilder(
private fun javaAnySetter(
target: KSClassDeclaration,
- mixin: KSClassDeclaration,
+ mixin: KSClassDeclaration?,
): JvmMember? {
val methods = effectiveMethods(target, mixin, JSON_ANY_SETTER)
if (methods.size > 1) {
@@ -567,7 +765,7 @@ internal class KspModelBuilder(
private fun javaCreator(
target: KSClassDeclaration,
- mixin: KSClassDeclaration,
+ mixin: KSClassDeclaration?,
): JvmMember? {
val candidates = ArrayList<KSFunctionDeclaration>()
target
@@ -633,9 +831,10 @@ internal class KspModelBuilder(
private fun hasEffectiveAnnotation(
target: KSFunctionDeclaration,
- mixin: KSClassDeclaration,
+ mixin: KSClassDeclaration?,
annotation: String,
): Boolean {
+ if (mixin == null) return hasAnnotation(target, annotation)
val source = matchingMixinFunction(target, mixin)
if (source != null) {
if (hasAnnotation(source, annotation)) return true
@@ -646,7 +845,7 @@ internal class KspModelBuilder(
private fun hasEffectiveJsonAnnotation(
target: KSFunctionDeclaration,
- mixin: KSClassDeclaration,
+ mixin: KSClassDeclaration?,
): Boolean =
effectiveAnnotations(target, mixin).any {
annotationName(it).startsWith(JSON_ANNOTATION_PACKAGE)
diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
index 6867ca8fb..1bcd3fb40 100644
--- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
+++ b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/Model.kt
@@ -43,4 +43,12 @@ internal data class JsonModel(
val retainedTypes: Set<String>,
val codecTypes: Set<String>,
val containerTypes: Set<String>,
+ val aggregating: Boolean = false,
+)
+
+internal data class JavaSubtypeGeneration(
+ val packageName: String,
+ val simpleName: String,
+ val mixinSourceName: String,
+ val originatingFiles: List<KSFile>,
)
diff --git a/kotlin/fory-json-kotlin-ksp/src/test/kotlin/org/apache/fory/json/kotlin/ksp/KspTestSupport.kt b/kotlin/fory-json-kotlin-ksp/src/test/kotlin/org/apache/fory/json/kotlin/ksp/KspTestSupport.kt
index 45d47f32b..45eec0d5c 100644
--- a/kotlin/fory-json-kotlin-ksp/src/test/kotlin/org/apache/fory/json/kotlin/ksp/KspTestSupport.kt
+++ b/kotlin/fory-json-kotlin-ksp/src/test/kotlin/org/apache/fory/json/kotlin/ksp/KspTestSupport.kt
@@ -101,6 +101,7 @@ internal fun jsonModel(
retainedTypes: Set<String> = emptySet(),
codecTypes: Set<String> = emptySet(),
containerTypes: Set<String> = emptySet(),
+ aggregating: Boolean = false,
): JsonModel =
JsonModel(
targetBinaryName = targetBinaryName,
@@ -112,6 +113,7 @@ internal fun jsonModel(
retainedTypes = retainedTypes,
codecTypes = codecTypes,
containerTypes = containerTypes,
+ aggregating = aggregating,
)
internal object SilentLogger : KSPLogger {
diff --git a/kotlin/fory-json-kotlin-ksp/src/test/kotlin/org/apache/fory/json/kotlin/ksp/ProcessorResourceTest.kt b/kotlin/fory-json-kotlin-ksp/src/test/kotlin/org/apache/fory/json/kotlin/ksp/ProcessorResourceTest.kt
index baa510482..aa11fad85 100644
--- a/kotlin/fory-json-kotlin-ksp/src/test/kotlin/org/apache/fory/json/kotlin/ksp/ProcessorResourceTest.kt
+++ b/kotlin/fory-json-kotlin-ksp/src/test/kotlin/org/apache/fory/json/kotlin/ksp/ProcessorResourceTest.kt
@@ -42,6 +42,7 @@ class ProcessorResourceTest {
fun writesOwnedResources() {
val directSource = sourceFile("Profile.kt")
val sealedSource = sourceFile("Shape.kt")
+ val branchSource = sourceFile("ShapeBranch.kt")
val mixinSource = sourceFile("ProfileMixin.kt")
val mixinTargetSource = sourceFile("ExternalProfile.java")
val directCodecTypes = codecTypes("example.direct")
@@ -56,9 +57,10 @@ class ProcessorResourceTest {
),
jsonModel(
targetBinaryName = "example.Shape",
- originatingFiles = listOf(sealedSource),
+ originatingFiles = listOf(sealedSource, branchSource),
retainedAnnotations = setOf("org.apache.fory.json.annotation.JsonSubTypes"),
retainedTypes = setOf("example.Circle"),
+ aggregating = true,
),
jsonModel(
targetBinaryName = "example.ExternalProfile",
@@ -104,7 +106,7 @@ class ProcessorResourceTest {
val path = R8RulesWriter.resourcePath(model)
assertEquals(R8RulesWriter.write(model), generator.text(path))
val dependencies = generator.dependenciesByPath.getValue(path)
- assertFalse(dependencies.aggregating, path)
+ assertEquals(model.aggregating, dependencies.aggregating, path)
assertFalse(dependencies.isAllSources, path)
assertEquals(model.originatingFiles.size, dependencies.originatingFiles.size, path)
model.originatingFiles.forEachIndexed { index, source ->
@@ -124,6 +126,37 @@ class ProcessorResourceTest {
)
}
+ @Test
+ fun writesJavaSubtypeGeneration() {
+ val mixinSource = sourceFile("ShapeMixin.kt")
+ val targetSource = sourceFile("Shape.java")
+ val generation =
+ JavaSubtypeGeneration(
+ packageName = "mixins",
+ simpleName = "ShapeMixin_ForyJsonSubtypeGeneration",
+ mixinSourceName = "mixins.ShapeMixin",
+ originatingFiles = listOf(mixinSource, targetSource),
+ )
+ val generator = RecordingCodeGenerator()
+ val processor =
+ ForyJsonKotlinSymbolProcessorProvider()
+ .create(
+ SymbolProcessorEnvironment(emptyMap(), KotlinVersion.CURRENT, generator, SilentLogger)
+ )
+ val write = processor.javaClass.getDeclaredMethod("write", JavaSubtypeGeneration::class.java)
+ write.isAccessible = true
+
+ write.invoke(processor, generation)
+
+ val path = "mixins/ShapeMixin_ForyJsonSubtypeGeneration.java"
+ val source = generator.text(path)
+ assertTrue(source.contains("GeneratedJsonSubtypeTable.Generation"), source)
+ assertTrue(source.contains("mixin = \"mixins.ShapeMixin\""), source)
+ val dependencies = generator.dependenciesByPath.getValue(path)
+ assertTrue(dependencies.aggregating)
+ assertEquals(2, dependencies.originatingFiles.size)
+ }
+
private fun codecTypes(packageName: String): Set<String> =
linkedSetOf(
"$packageName.MapValueCodec",
@@ -142,7 +175,6 @@ class ProcessorResourceTest {
}"""
assertEquals(1, rules.split(exactRule).size - 1, codecType)
}
- assertEquals(codecTypes.size, rules.lineSequence().count { it == " public <init>();" })
assertFalse(rules.contains('*'), rules)
assertFalse(rules.contains("JsonCodec\$NoJsonValueCodec"), rules)
assertFalse(rules.contains("JsonCodec\$NoMapKeyCodec"), rules)
diff --git a/kotlin/fory-json-kotlin/src/main/kotlin/org/apache/fory/json/kotlin/KotlinJsonCodecFactory.kt b/kotlin/fory-json-kotlin/src/main/kotlin/org/apache/fory/json/kotlin/KotlinJsonCodecFactory.kt
index 2c6cd97b9..70c2e8a12 100644
--- a/kotlin/fory-json-kotlin/src/main/kotlin/org/apache/fory/json/kotlin/KotlinJsonCodecFactory.kt
+++ b/kotlin/fory-json-kotlin/src/main/kotlin/org/apache/fory/json/kotlin/KotlinJsonCodecFactory.kt
@@ -99,6 +99,19 @@ internal object KotlinJsonCodecFactory : JsonCodecFactory {
return KotlinValueClassCodecs.create(type)
}
if (rawType.getAnnotation(Metadata::class.java) == null) return null
+ if (resolver.isInferredSubtype(rawType)) {
+ resolver.cachedInferredSubtypeCodec(type, this)?.let {
+ return it
+ }
+ val table = KotlinSealedSubtypes.discover(rawType)
+ return resolver.createInferredSubtypeCodec(
+ type,
+ table.classes,
+ table.names,
+ this,
+ null,
+ )
+ }
return resolver.createObjectCodec(
type,
KotlinMetadataModels.objectModel(type, resolver.creatorDeclarations(rawType)),
diff --git a/kotlin/fory-json-kotlin/src/main/kotlin/org/apache/fory/json/kotlin/KotlinSealedSubtypes.kt b/kotlin/fory-json-kotlin/src/main/kotlin/org/apache/fory/json/kotlin/KotlinSealedSubtypes.kt
new file mode 100644
index 000000000..2ea40f967
--- /dev/null
+++ b/kotlin/fory-json-kotlin/src/main/kotlin/org/apache/fory/json/kotlin/KotlinSealedSubtypes.kt
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.fory.json.kotlin
+
+import java.lang.reflect.Modifier
+import java.util.Collections
+import java.util.IdentityHashMap
+import kotlin.metadata.Modality
+import kotlin.metadata.modality
+import org.apache.fory.json.ForyJsonException
+
+/** Cold sealed-closure producer backed by the same Kotlin metadata as object models. */
+internal object KotlinSealedSubtypes {
+ internal data class Table(val classes: Array<Class<*>>, val names: Array<String>)
+
+ fun discover(root: Class<*>): Table {
+ val metadata = KotlinMetadataTypes.classMetadata(root).kmClass
+ if (metadata.modality != Modality.SEALED) {
+ throw ForyJsonException("Empty @JsonSubTypes requires a sealed Kotlin type ${root.name}")
+ }
+ // Kotlin metadata is trusted static schema input retained by the application build. JSON
+ // input cannot contribute a class name and later selects only a validated logical name.
+ val classes = ArrayList<Class<*>>()
+ val names = ArrayList<String>()
+ val visited = Collections.newSetFromMap(IdentityHashMap<Class<*>, Boolean>())
+ collect(root, metadata.sealedSubclasses, classes, names, visited)
+ return Table(classes.toTypedArray(), names.toTypedArray())
+ }
+
+ private fun collect(
+ root: Class<*>,
+ directNames: List<String>,
+ classes: MutableList<Class<*>>,
+ names: MutableList<String>,
+ visited: MutableSet<Class<*>>,
+ ) {
+ for (metadataName in directNames) {
+ val subtype = load(root, metadataName)
+ if (!visited.add(subtype)) continue
+ val model = KotlinMetadataTypes.classMetadata(subtype).kmClass
+ val concrete = !subtype.isInterface && !Modifier.isAbstract(subtype.modifiers)
+ if (concrete) {
+ classes += subtype
+ names += sourceSimpleName(metadataName)
+ }
+ if (model.modality == Modality.SEALED) {
+ collect(root, model.sealedSubclasses, classes, names, visited)
+ } else if (!concrete) {
+ throw ForyJsonException(
+ "Sealed Kotlin JSON hierarchy has an open abstract branch ${subtype.name}"
+ )
+ }
+ }
+ }
+
+ private fun load(root: Class<*>, metadataName: String): Class<*> {
+ val binaryName = binaryName(metadataName)
+ return try {
+ Class.forName(binaryName, false, root.classLoader)
+ } catch (cause: ClassNotFoundException) {
+ throw ForyJsonException(
+ "Cannot resolve Kotlin sealed subtype $binaryName from ${root.name}",
+ cause,
+ )
+ }
+ }
+
+ private fun binaryName(metadataName: String): String {
+ val packageEnd = metadataName.lastIndexOf('/')
+ val packageName =
+ if (packageEnd < 0) "" else metadataName.substring(0, packageEnd).replace('/', '.') + "."
+ return packageName + metadataName.substring(packageEnd + 1).replace('.', '$')
+ }
+
+ private fun sourceSimpleName(metadataName: String): String =
+ metadataName.substringAfterLast('/').substringAfterLast('.')
+}
diff --git a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinSealedRuntimeTest.kt b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinSealedRuntimeTest.kt
index 75fdb7e11..ec091c91a 100644
--- a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinSealedRuntimeTest.kt
+++ b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinSealedRuntimeTest.kt
@@ -79,6 +79,24 @@ sealed interface InvalidPropertyShape
@JvmInline value class InvalidPropertyNumber(val value: Int) : InvalidPropertyShape
+@JsonSubTypes(property = "kind") sealed interface InferredShape
+
+data class InferredCircle(val radius: Int) : InferredShape
+
+data object InferredMarker : InferredShape
+
+sealed interface InferredBranch : InferredShape
+
+data class InferredLeaf(val value: String) : InferredBranch
+
+open class InferredOpen(val value: Int) : InferredShape
+
+class InferredDescendant(value: Int) : InferredOpen(value)
+
+@JsonSubTypes(property = "kind") sealed interface InvalidInferredShape
+
+abstract class OpenAbstractBranch : InvalidInferredShape
+
class KotlinSealedRuntimeTest {
@Test
fun propertyShape() {
@@ -162,4 +180,52 @@ class KotlinSealedRuntimeTest {
json.fromJson("{\"kind\":\"number\",\"value\":1}", jsonTypeRef<InvalidPropertyShape>())
}
}
+
+ @Test
+ fun inferredClosure() {
+ forEachJsonMode { json ->
+ val type = jsonTypeRef<InferredShape>()
+ val values =
+ listOf<InferredShape>(
+ InferredCircle(3),
+ InferredMarker,
+ InferredLeaf("leaf"),
+ InferredOpen(4),
+ )
+ val names = listOf("InferredCircle", "InferredMarker", "InferredLeaf", "InferredOpen")
+ values.zip(names).forEach { (value, name) ->
+ val text = json.toJson(value, type)
+ assertEquals(true, text.contains("\"kind\":\"$name\""), text)
+ for (decoded in
+ listOf(json.fromJson(text, type), json.fromJson(text.toByteArray(), type))) {
+ assertEquals(value::class, decoded::class)
+ if (value is InferredOpen) assertEquals(value.value, (decoded as InferredOpen).value)
+ else assertEquals(value, decoded)
+ }
+ }
+ assertFailsWith<ForyJsonException> { json.toJson(InferredDescendant(5), type) }
+ }
+ }
+
+ @Test
+ fun inferredCheckerSubset() {
+ KotlinJsonTestMode.entries.forEach { mode ->
+ val json =
+ newKotlinJson(mode) {
+ withTypeChecker { name, _ -> name != InferredMarker::class.java.name }
+ }
+ val type = jsonTypeRef<InferredShape>()
+ assertFailsWith<ForyJsonException> { json.toJson(InferredMarker, type) }
+ assertEquals(
+ InferredLeaf("accepted"),
+ json.fromJson("{\"kind\":\"InferredLeaf\",\"value\":\"accepted\"}", type),
+ )
+ }
+ }
+
+ @Test
+ fun rejectsInvalidInferredHierarchy() {
+ val json = newKotlinJson(KotlinJsonTestMode.INTERPRETED)
+ assertFailsWith<ForyJsonException> { json.fromJson("{}", jsonTypeRef<InvalidInferredShape>()) }
+ }
}
diff --git a/scala/fory-json-scala/src/main/scala-3/org/apache/fory/json/scala/ScalaJsonCodec.scala b/scala/fory-json-scala/src/main/scala-3/org/apache/fory/json/scala/ScalaJsonCodec.scala
index 651a90c1d..5f89ff12b 100644
--- a/scala/fory-json-scala/src/main/scala-3/org/apache/fory/json/scala/ScalaJsonCodec.scala
+++ b/scala/fory-json-scala/src/main/scala-3/org/apache/fory/json/scala/ScalaJsonCodec.scala
@@ -23,7 +23,7 @@ import org.apache.fory.json.{ForyJsonBuilder, JsonCodecFactory}
import scala.reflect.ClassTag
-/** Compile-time JSON schema for one closed Scala 3 enum. */
+/** Compile-time JSON schema for a Scala 3 enum or sealed hierarchy. */
trait ScalaJsonCodec[T] extends JsonCodecFactory
object ScalaJsonCodec {
@@ -32,7 +32,7 @@ object ScalaJsonCodec {
}
extension (builder: ForyJsonBuilder)
- /** Derives and registers a closed schema for a third-party Scala 3 enum. */
+ /** Derives and registers a closed schema for a third-party Scala 3 enum or sealed hierarchy. */
inline def register[T](using tag: ClassTag[T]): ForyJsonBuilder =
builder.registerCodec(
tag.runtimeClass.asInstanceOf[Class[T]],
diff --git a/scala/fory-json-scala/src/main/scala-3/org/apache/fory/json/scala/internal/DerivedScalaJsonCodec.scala b/scala/fory-json-scala/src/main/scala-3/org/apache/fory/json/scala/internal/DerivedScalaJsonCodec.scala
index 2b2a2a0ef..77466e51c 100644
--- a/scala/fory-json-scala/src/main/scala-3/org/apache/fory/json/scala/internal/DerivedScalaJsonCodec.scala
+++ b/scala/fory-json-scala/src/main/scala-3/org/apache/fory/json/scala/internal/DerivedScalaJsonCodec.scala
@@ -39,11 +39,28 @@ private[scala] final class DerivedScalaJsonCodec[T](
caseClasses.length == 0 || caseClasses.length != caseNames.length ||
caseClasses.length != singletonCases.length
)
- throw new IllegalArgumentException("A derived Scala enum must have a non-empty case table")
+ throw new IllegalArgumentException("A derived Scala schema must have a non-empty case table")
private val classes = caseClasses.clone()
private val names = caseNames.clone()
private val singletons = singletonCases.clone()
+ private var sortIndex = 1
+ while (sortIndex < classes.length) {
+ val sortedClass = classes(sortIndex)
+ val sortedName = names(sortIndex)
+ val sortedSingleton = singletons(sortIndex)
+ var prior = sortIndex
+ while (prior > 0 && classes(prior - 1).getName.compareTo(sortedClass.getName) > 0) {
+ classes(prior) = classes(prior - 1)
+ names(prior) = names(prior - 1)
+ singletons(prior) = singletons(prior - 1)
+ prior -= 1
+ }
+ classes(prior) = sortedClass
+ names(prior) = sortedName
+ singletons(prior) = sortedSingleton
+ sortIndex += 1
+ }
private val handled: JList[Class[_]] = {
val result = new ArrayList[Class[_]](classes.length)
val classSet = new HashSet[Class[_]](classes.length * 2)
@@ -55,19 +72,19 @@ private[scala] final class DerivedScalaJsonCodec[T](
if (
caseClass == null || !rootType.isAssignableFrom(caseClass) ||
Modifier.isAbstract(caseClass.getModifiers)
- ) throw new IllegalArgumentException(s"Invalid derived Scala enum case $caseClass")
+ ) throw new IllegalArgumentException(s"Invalid derived Scala case $caseClass")
if (name == null || name.isEmpty || !nameSet.add(name))
- throw new IllegalArgumentException(s"Invalid derived Scala enum case name $name")
+ throw new IllegalArgumentException(s"Invalid derived Scala case name $name")
val singleton = singletons(index)
if (singleton != null && singleton.getClass != caseClass)
- throw new IllegalArgumentException(s"Invalid derived Scala enum singleton $name")
+ throw new IllegalArgumentException(s"Invalid derived Scala singleton $name")
if (classSet.add(caseClass)) result.add(caseClass)
else {
var prior = 0
while (classes(prior) != caseClass) prior += 1
if (singleton == null || singletons(prior) == null)
throw new IllegalArgumentException(
- s"Duplicate derived Scala enum case ${caseClass.getName}"
+ s"Duplicate derived Scala case ${caseClass.getName}"
)
}
index += 1
@@ -97,6 +114,15 @@ private[scala] final class DerivedScalaJsonCodec[T](
): JsonValueCodec[_] = {
val rawType = typeRef.getRawType
if (rawType == rootType) {
+ if (resolver.isInferredSubtype(rootType)) {
+ return resolver.createInferredSubtypeCodec(
+ typeRef,
+ classes.clone(),
+ names.clone(),
+ null,
+ null
+ )
+ }
return new ClosedSubtypeCodec(
rootType,
new JsonSubTypesInfo(Inclusion.WRAPPER_OBJECT, "", classes.clone(), names.clone()),
@@ -107,7 +133,7 @@ private[scala] final class DerivedScalaJsonCodec[T](
}
val index = classes.indexOf(rawType)
if (index < 0)
- throw new ForyJsonException(s"Derived Scala enum codec expected ${rootType.getName}")
+ throw new ForyJsonException(s"Derived Scala codec expected ${rootType.getName}")
val singleton = singletons(index)
if (singleton == null) ScalaObjectModels.caseClassCodec(typeRef, resolver)
else ScalaObjectModels.fixedCodec(typeRef, resolver, singleton)
diff --git a/scala/fory-json-scala/src/main/scala-3/org/apache/fory/json/scala/internal/ScalaJsonCodecMacros.scala b/scala/fory-json-scala/src/main/scala-3/org/apache/fory/json/scala/internal/ScalaJsonCodecMacros.scala
index 2e73d60c8..c2719e197 100644
--- a/scala/fory-json-scala/src/main/scala-3/org/apache/fory/json/scala/internal/ScalaJsonCodecMacros.scala
+++ b/scala/fory-json-scala/src/main/scala-3/org/apache/fory/json/scala/internal/ScalaJsonCodecMacros.scala
@@ -28,18 +28,50 @@ private[scala] object ScalaJsonCodecMacros {
import quotes.reflect.*
val root = TypeRepr.of[T].dealias.typeSymbol
- if (!root.flags.is(Flags.Enum))
- report.errorAndAbort(s"${root.fullName} is not a Scala 3 enum")
+ val enumRoot = root.flags.is(Flags.Enum)
+ if (!enumRoot && !root.flags.is(Flags.Sealed))
+ report.errorAndAbort(s"${root.fullName} is not a Scala 3 enum or sealed type")
+ if (!enumRoot && !root.flags.is(Flags.Abstract) && !root.flags.is(Flags.Trait))
+ report.errorAndAbort(s"${root.fullName} must be an abstract sealed class or sealed trait")
- val cases = root.children.filter(_.flags.is(Flags.Case))
+ // Compiler symbols are trusted static schema metadata. JSON input never participates in this
+ // traversal and later selects only a logical name from the validated generated table.
+ val cases =
+ if (enumRoot) root.children.filter(_.flags.is(Flags.Case))
+ else {
+ val result = scala.collection.mutable.ArrayBuffer.empty[Symbol]
+ val visited = scala.collection.mutable.HashSet.empty[Symbol]
+ def collect(owner: Symbol): Unit =
+ owner.children.foreach { child =>
+ if (visited.add(child)) {
+ val concrete =
+ !child.flags.is(Flags.Abstract) && !child.flags.is(Flags.Trait)
+ if (concrete) result += child
+ if (child.flags.is(Flags.Sealed)) collect(child)
+ else if (!concrete)
+ report.errorAndAbort(
+ s"Sealed JSON hierarchy has an open abstract branch ${child.fullName}"
+ )
+ }
+ }
+ collect(root)
+ result.toList
+ }
if (cases.isEmpty)
- report.errorAndAbort(s"${root.fullName} has no closed enum cases")
+ report.errorAndAbort(s"${root.fullName} has no concrete closed cases")
val rootClass =
Literal(ClassOfConstant(TypeRepr.of[T].dealias)).asExprOf[Class[?]]
val caseExpressions = cases.map { child =>
if (child.primaryConstructor == Symbol.noSymbol) {
- val value = Select.unique(Ref(root.companionModule), child.name).asExpr
+ val value =
+ if (enumRoot) Select.unique(Ref(root.companionModule), child.name).asExpr
+ else {
+ val module = child.companionModule
+ if (module == Symbol.noSymbol)
+ report.errorAndAbort(s"Cannot resolve Scala singleton ${child.fullName}")
+ Ref(module).asExpr
+ }
val singleton = '{ $value.asInstanceOf[AnyRef] }
('{ $singleton.getClass }, singleton)
} else {
diff --git a/scala/fory-json-scala/src/main/scala/org/apache/fory/json/scala/internal/ScalaTypeCodecFactory.scala b/scala/fory-json-scala/src/main/scala/org/apache/fory/json/scala/internal/ScalaTypeCodecFactory.scala
index acc51ab75..b2851fa68 100644
--- a/scala/fory-json-scala/src/main/scala/org/apache/fory/json/scala/internal/ScalaTypeCodecFactory.scala
+++ b/scala/fory-json-scala/src/main/scala/org/apache/fory/json/scala/internal/ScalaTypeCodecFactory.scala
@@ -76,6 +76,16 @@ private[scala] object ScalaTypeCodecFactory extends JsonCodecFactory {
if (tupleArity >= 1) return new ScalaTupleCodec(tupleArity, rawType, runtimeType)
if (name == "scala.Tuple$package$EmptyTuple$") return new ScalaEmptyTupleCodec(rawType)
+ if (resolver.isInferredSubtype(rawType)) {
+ val derivedCodec = ScalaDerivedCodec.find(rawType)
+ if (derivedCodec == null)
+ throw ScalaTypeSupport.unsupported(
+ typeRef,
+ "sealed hierarchy requires derives ScalaJsonCodec or builder register"
+ )
+ return derivedCodec.create(typeRef, resolver, runtimeType)
+ }
+
if (classOf[scala.collection.Map[_, _]].isAssignableFrom(rawType)) {
val selection = mapKind(rawType, runtimeType)
if (selection == null)
diff --git a/scala/fory-json-scala/src/test/scala-3/org/apache/fory/json/scala/ScalaJsonDerivationSuite.scala b/scala/fory-json-scala/src/test/scala-3/org/apache/fory/json/scala/ScalaJsonDerivationSuite.scala
index 609f146a8..8009e387b 100644
--- a/scala/fory-json-scala/src/test/scala-3/org/apache/fory/json/scala/ScalaJsonDerivationSuite.scala
+++ b/scala/fory-json-scala/src/test/scala-3/org/apache/fory/json/scala/ScalaJsonDerivationSuite.scala
@@ -22,6 +22,7 @@ package org.apache.fory.json.scala
import java.util.concurrent.atomic.AtomicBoolean
import org.apache.fory.json.{ForyJsonException, JsonCodecFactory}
+import org.apache.fory.json.annotation.JsonSubTypes
import org.apache.fory.json.codec.{AbstractJsonValueCodec, JsonValueCodec}
import org.apache.fory.json.reader.JsonReader
import org.apache.fory.json.resolver.JsonTypeResolver
@@ -46,6 +47,29 @@ enum StatefulResult derives ScalaJsonCodec {
final case class StatefulEnvelope(value: StatefulResult)
+@JsonSubTypes(property = "kind")
+sealed trait InferredEvent derives ScalaJsonCodec
+
+final case class InferredMessage(value: String) extends InferredEvent
+
+case object InferredIdle extends InferredEvent
+
+sealed trait InferredBranch extends InferredEvent
+
+final case class InferredLeaf(value: Int) extends InferredBranch
+
+class InferredOpen() extends InferredEvent {
+ var value: Int = 0
+}
+
+final class InferredDescendant() extends InferredOpen
+
+sealed class ConcreteSealed() extends InferredEvent {
+ var value: Int = 0
+}
+
+final class ConcreteLeaf() extends ConcreteSealed
+
enum ExternalResult {
case Ok(value: String)
case Error(code: Int)
@@ -250,4 +274,53 @@ class ScalaJsonDerivationSuite extends AnyFunSuite {
assert(json.toJson(DisplayColor.Red) == "\"Red\"")
assert(json.fromJson("\"Blue\"", classOf[DisplayColor]) == DisplayColor.Blue)
}
+
+ test("derived sealed hierarchy uses inferred subtype names") {
+ val runtimes = Seq(
+ ForyJsonScala.builder().withCodegen(false).build(),
+ ForyJsonScala.builder().withAsyncCompilation(false).build()
+ )
+ val open = new InferredOpen()
+ open.value = 4
+ val concrete = new ConcreteSealed()
+ concrete.value = 5
+ val leaf = new ConcreteLeaf()
+ leaf.value = 6
+ val values = Seq[(InferredEvent, String)](
+ InferredMessage("ready") -> "InferredMessage",
+ InferredIdle -> "InferredIdle",
+ InferredLeaf(3) -> "InferredLeaf",
+ open -> "InferredOpen",
+ concrete -> "ConcreteSealed",
+ leaf -> "ConcreteLeaf"
+ )
+ runtimes.foreach { json =>
+ values.foreach { (value, name) =>
+ val text = json.toJson(value, classOf[InferredEvent])
+ assert(text.contains(s"\"kind\":\"$name\""), text)
+ val decoded = json.fromJson(text, classOf[InferredEvent])
+ assert(decoded.getClass == value.getClass)
+ }
+ assertThrows[ForyJsonException](
+ json.toJson(new InferredDescendant(), classOf[InferredEvent])
+ )
+ }
+ }
+
+ test("type checker narrows a derived sealed hierarchy") {
+ val json = ForyJsonScala
+ .builder()
+ .withCodegen(false)
+ .withTypeChecker((name, _) => name != InferredIdle.getClass.getName)
+ .build()
+ assertThrows[ForyJsonException](
+ json.toJson(InferredIdle, classOf[InferredEvent])
+ )
+ assert(
+ json.fromJson(
+ "{\"kind\":\"InferredLeaf\",\"value\":7}",
+ classOf[InferredEvent]
+ ) == InferredLeaf(7)
+ )
+ }
}
diff --git a/scala/fory-json-scala/src/test/scala-3/org/apache/fory/json/scala/ScalaJsonNativeImageMain.scala b/scala/fory-json-scala/src/test/scala-3/org/apache/fory/json/scala/ScalaJsonNativeImageMain.scala
index 225cd5170..ce23afe82 100644
--- a/scala/fory-json-scala/src/test/scala-3/org/apache/fory/json/scala/ScalaJsonNativeImageMain.scala
+++ b/scala/fory-json-scala/src/test/scala-3/org/apache/fory/json/scala/ScalaJsonNativeImageMain.scala
@@ -20,7 +20,7 @@
package org.apache.fory.json.scala
import org.apache.fory.json.ForyJson
-import org.apache.fory.json.annotation.{ForyJsonProvider, JsonProperty, JsonType}
+import org.apache.fory.json.annotation.{ForyJsonProvider, JsonProperty, JsonSubTypes, JsonType}
@JsonType
case class NativeNode(value: Int, next: Option[NativeNode] = None)
@@ -37,6 +37,13 @@ enum NativeResult derives ScalaJsonCodec {
case Pending
}
+@JsonSubTypes(property = "kind")
+sealed trait NativeEvent derives ScalaJsonCodec
+
+final case class NativeMessage(value: String) extends NativeEvent
+
+case object NativeIdle extends NativeEvent
+
@JsonType
enum NativeColor {
case Red, Blue
@@ -63,6 +70,13 @@ object ScalaJsonNativeImageMain {
val result: NativeResult = NativeResult.Ok("ready")
require(json.fromJson(json.toJson(result), classOf[NativeResult]) == result)
+ val event: NativeEvent = NativeMessage("sealed")
+ require(
+ json.fromJson(json.toJson(event, classOf[NativeEvent]), classOf[NativeEvent]) == event
+ )
+ require(
+ json.fromJson(json.toJson(NativeIdle, classOf[NativeEvent]), classOf[NativeEvent]) eq NativeIdle
+ )
require(json.fromJson(json.toJson(NativeColor.Blue), classOf[NativeColor]) == NativeColor.Blue)
println("Fory Scala JSON native image succeeded")
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@fory.apache.org
For additional commands, e-mail: commits-help@fory.apache.org