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/07/16 12:12:56 UTC
(fory) branch main updated: feat(java): add json mixin support (#3863)
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 835b85209 feat(java): add json mixin support (#3863)
835b85209 is described below
commit 835b852090f61e99c60131b1086411734407689d
Author: Shawn Yang <sh...@gmail.com>
AuthorDate: Thu Jul 16 17:42:53 2026 +0530
feat(java): add json mixin support (#3863)
## Why?
## What does this PR do?
## Related issues
## 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
---
docs/guide/java/android-support.md | 49 +-
docs/guide/java/graalvm-support.md | 52 +-
docs/guide/java/json-support.md | 115 +-
integration_tests/android_tests/README.md | 6 +-
integration_tests/android_tests/proguard-rules.pro | 1 +
.../fory/android/ForyAndroidInstrumentedTest.java | 5 +
.../apache/fory/android/AndroidJsonScenarios.java | 159 +++
integration_tests/graalvm_tests/README.md | 8 +-
.../org/apache/fory/graalvm/ForyJsonExample.java | 259 +++++
java/fory-annotation-processor/README.md | 40 +-
.../annotation/processing/ForyStructProcessor.java | 4 +
.../processing/GeneratedJsonCodecSourceWriter.java | 196 ++--
.../annotation/processing/GeneratedTypeNames.java | 10 +
.../processing/JsonMixinAnnotations.java | 578 ++++++++++
.../annotation/processing/JsonTypeProcessor.java | 565 ++++++++--
.../processing/JsonTypeProcessorTest.java | 420 +++++++-
java/fory-json/README.md | 95 +-
.../java/org/apache/fory/json/ForyJsonBuilder.java | 41 +
.../main/java/org/apache/fory/json/JsonConfig.java | 66 +-
.../org/apache/fory/json/annotation/JsonMixin.java | 68 ++
.../fory/json/annotation/JsonMixinRemove.java | 57 +
.../org/apache/fory/json/annotation/JsonType.java | 8 +-
.../org/apache/fory/json/codec/ObjectCodec.java | 19 +-
.../apache/fory/json/codec/ObjectCodecBuilder.java | 342 +++---
.../fory/json/meta/JsonCreatorDeclaration.java | 7 +-
.../json/resolver/GeneratedJsonCodecFactories.java | 50 +-
.../fory/json/resolver/JsonMixinAnnotations.java | 502 +++++++++
.../fory/json/resolver/JsonSharedRegistry.java | 256 +++--
.../fory/json/resolver/JsonTypeResolver.java | 1 +
.../fory/json/resolver/JsonValueDeclaration.java | 80 +-
.../fory/json/codec/ForyJsonGraalVMFeature.java | 305 +++++-
.../apache/fory/json/JsonAsyncCompilationTest.java | 1 +
.../java/org/apache/fory/json/JsonMixinTest.java | 1133 ++++++++++++++++++++
.../java/org/apache/fory/json/JsonTestSupport.java | 2 +
34 files changed, 4993 insertions(+), 507 deletions(-)
diff --git a/docs/guide/java/android-support.md b/docs/guide/java/android-support.md
index 25421b25e..0a45194ae 100644
--- a/docs/guide/java/android-support.md
+++ b/docs/guide/java/android-support.md
@@ -100,6 +100,40 @@ public final class Invoice {
}
```
+The same processor supports Fory JSON Mixins. A Mixin declares one exact target and is registered
+on the runtime that should use it:
+
+```java
+import org.apache.fory.json.ForyJson;
+import org.apache.fory.json.annotation.JsonBase64;
+import org.apache.fory.json.annotation.JsonMixin;
+
+@JsonMixin(target = ThirdPartyInvoice.class)
+public abstract class ThirdPartyInvoiceMixin {
+ @JsonBase64 byte[] signature;
+}
+
+ForyJson json =
+ ForyJson.builder().registerMixin(ThirdPartyInvoiceMixin.class).build();
+```
+
+Compile every non-empty Mixin source with `fory-annotation-processor`. The processor emits exact
+R8 rules and any pair-specific target operations that the runtime can use. Registered codecs,
+effective type codecs, and built-in mappings keep their normal runtime precedence. An empty Mixin
+produces no generated output.
+
+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 runtime selects the
+pair-specific companion for a non-empty registered Mixin instead of combining the overlay with the
+target's direct companion.
+
+Only one source is enabled for an exact target in one built runtime. 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 runtime uses
+only the last registered source.
+
+Use the processor-generated R8 rules for non-empty Mixins instead of broad package keep rules.
+
Ordinary non-Record classes that omit `JsonType` can supply equivalent exact rules themselves.
Retain every model
constructor, field, method, generic signature, declaration annotation, and parameter annotation used
@@ -137,13 +171,14 @@ supports mutable classes, creator-backed classes, and Records through their norm
construction paths. When the containing model and its unwrapped children use `JsonType`, their
generated companions supply those operations.
-Android-desugared Records require a direct `@JsonType` annotation and the annotation processor.
-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 companion identifies the propagated component accessor and calls
-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`. Use a complete value codec for deeper nested behavior.
+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 companion
+identifies the propagated component accessor and calls 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.
## Static Generated Serializers
diff --git a/docs/guide/java/graalvm-support.md b/docs/guide/java/graalvm-support.md
index 553f616f4..7da3e7a2a 100644
--- a/docs/guide/java/graalvm-support.md
+++ b/docs/guide/java/graalvm-support.md
@@ -80,6 +80,43 @@ public class JsonExample {
}
```
+The processor also supports Fory JSON Mixins for models that cannot be modified:
+
+```java
+import org.apache.fory.json.ForyJson;
+import org.apache.fory.json.annotation.JsonMixin;
+import org.apache.fory.json.annotation.JsonProperty;
+
+@JsonMixin(target = ThirdPartyUser.class)
+public abstract class ThirdPartyUserMixin {
+ @JsonProperty("user_id")
+ long id;
+}
+
+public class JsonExample {
+ public static void main(String[] args) {
+ ForyJson json =
+ ForyJson.builder().registerMixin(ThirdPartyUserMixin.class).build();
+ ThirdPartyUser user = json.fromJson("{\"user_id\":1}", ThirdPartyUser.class);
+ System.out.println(json.toJson(user));
+ }
+}
+```
+
+`JsonMixin` is a build-time entry point for its exact declared target, so the target does not need
+`JsonType` solely to use the Mixin. The registered Mixin class literal must be reachable from the
+application. The processor emits available target operations for each non-empty Mixin, and the
+Fory JSON Native Image Feature retains the effective runtime metadata. Normal runtime codec
+precedence still selects the representation. An empty Mixin produces no generated output.
+
+Only one source is enabled for an exact target in a built `ForyJson`. Later registration replaces
+an earlier source for subsequent `build()` calls; a runtime keeps the immutable snapshot it was
+built with. If the target also has a direct `JsonType` companion, a non-empty registered Mixin
+selects the pair-specific artifact instead of combining the overlay with the direct companion.
+
+Do not add application reflection configuration as a replacement for the generated configuration.
+The native executable resolves the same effective annotations as the JVM.
+
The processor generates direct property and creator operations. The `fory-json` artifact activates
its Native Image Feature automatically and retains the generated factories and required model
metadata. `@JsonType` is not inherited, so annotate every concrete runtime model. An annotated base
@@ -106,17 +143,20 @@ on the JVM and Android.
`JsonValue` fields and effective public zero-argument methods are supported, including matching
one-String `JsonCreator` constructors and public static factories. Fixed `JsonRawValue` fields and
getters support trusted raw String values, and fixed `JsonBase64` fields and getters support Base64
-`byte[]` values as on the JVM. Annotate each reachable owning model with `JsonType` so Native Image
-retains these members and the Base64 codec constructor. A directly annotated `JsonValue` Record
-uses its generated component accessor and canonical constructor operations.
+`byte[]` values as on the JVM. For direct target annotations, annotate each reachable owning model
+with `JsonType` so Native Image retains these members and the Base64 codec constructor. A directly
+annotated `JsonValue` Record uses its generated component accessor and canonical constructor
+operations. An effective declaration supplied by a Mixin uses the Mixin workflow above instead.
`JsonAnyProperty` and `JsonAnyGetter` flatten their Map into the enclosing object. Use
`@JsonCodec(valueCodec = ...)` on that field or getter to customize each dynamic value. A second
`JsonAnySetter` parameter may use the normal configuration for its own value shape.
-`JsonUnwrapped` uses the same interpreted behavior as on the JVM. Annotate the containing model and
-every unwrapped child or intermediate object with `JsonType` so each model receives its generated
-property and creator operations.
+`JsonUnwrapped` uses the same interpreted behavior as on the JVM. For direct target annotations,
+annotate the containing model and every unwrapped child or intermediate object with `JsonType` so
+each model receives its generated property and creator operations. A Mixin retains the
+unwrapped models reached by its effective schema; register a separate exact Mixin for a child only
+when that child's annotations also need an overlay.
Child codecs act on one direct level. `elementCodec` supports `Collection`, Java arrays, and
`AtomicReferenceArray`; `contentCodec` supports `Optional` and `AtomicReference`; `keyCodec` and
diff --git a/docs/guide/java/json-support.md b/docs/guide/java/json-support.md
index 042320821..6d3dbfe44 100644
--- a/docs/guide/java/json-support.md
+++ b/docs/guide/java/json-support.md
@@ -295,6 +295,7 @@ are rejected.
| `withConcurrencyLevel` | `max(1, 2 * processors)` | Reusable operation-state count |
| `withBufferSizeLimitBytes` | 2 MiB | Reusable capacity retained by each pooled writer |
| `registerCodec` | None | Exact-class complete-value codec |
+| `registerMixin` | None | Annotation Mixin for its exact declared target |
| `withTypeChecker` | None | Application policy in addition to Fory's disallow list |
Depth, concurrency, and retained buffer limits must be positive. The cached-field-name limit applies
@@ -309,8 +310,9 @@ disabled. Every other builder option keeps the behavior described above.
Fory JSON provides `JsonProperty`, `JsonPropertyOrder`, `JsonIgnore`, `JsonAnyProperty`,
`JsonAnyGetter`, `JsonAnySetter`, `JsonCreator`, `JsonCodec`, `JsonValue`, `JsonRawValue`,
-`JsonBase64`, `JsonUnwrapped`, `JsonSubTypes`, and `JsonType` under
-`org.apache.fory.json.annotation`. They are not Jackson, Gson, or Fory binary-protocol annotations.
+`JsonBase64`, `JsonUnwrapped`, and `JsonSubTypes` as mapping annotations under
+`org.apache.fory.json.annotation`. `JsonType` is a separate build-time generation marker. They are
+not Jackson, Gson, or Fory binary-protocol annotations.
```java
import java.util.LinkedHashMap;
@@ -323,6 +325,8 @@ import org.apache.fory.json.annotation.JsonBase64;
import org.apache.fory.json.annotation.JsonCodec;
import org.apache.fory.json.annotation.JsonCreator;
import org.apache.fory.json.annotation.JsonIgnore;
+import org.apache.fory.json.annotation.JsonMixin;
+import org.apache.fory.json.annotation.JsonMixinRemove;
import org.apache.fory.json.annotation.JsonProperty;
import org.apache.fory.json.annotation.JsonPropertyOrder;
import org.apache.fory.json.annotation.JsonRawValue;
@@ -342,6 +346,92 @@ to receive a companion. See
A directly annotated model that uses the default object codec requires that generated companion;
the runtime reports a configuration error if the processor output is missing.
+### Mixins
+
+Use a Mixin to configure an existing class without changing its source:
+
+```java
+import org.apache.fory.json.ForyJson;
+import org.apache.fory.json.annotation.JsonMixin;
+import org.apache.fory.json.annotation.JsonProperty;
+import org.apache.fory.json.annotation.JsonUnwrapped;
+
+@JsonMixin(target = ThirdPartyUser.class)
+abstract class ThirdPartyUserMixin {
+ @JsonProperty("user_id")
+ long id;
+
+ @JsonUnwrapped(prefix = "address_")
+ Address address;
+}
+
+ForyJson json = ForyJson.builder().registerMixin(ThirdPartyUserMixin.class).build();
+```
+
+The source must be a named abstract class or interface, must not be local or anonymous, must not
+extend or implement another type, and is never instantiated. An annotated source field, method,
+constructor, or parameter selects an existing target declaration by its Java signature. The source
+cannot invent a Java field, method, constructor, generic type, subtype implementation, or executable
+body. It may assign supported JSON roles such as property, creator, factory, subtype table, or value
+representation to matching declarations that already exist on the target. Every Java type, access
+operation, invocation, and runtime value still comes from the target.
+
+Registration is exact-target only. A base-class registration does not change a subclass, and an
+interface registration does not change an implementation. A subclass Mixin may select a member
+that the subclass inherits, but the resulting annotation applies only while that exact subclass is
+mapped.
+
+All Fory JSON mapping annotations are supported: `JsonAnyGetter`, `JsonAnyProperty`,
+`JsonAnySetter`, `JsonBase64`, `JsonCodec`, `JsonCreator`, `JsonIgnore`, `JsonProperty`,
+`JsonPropertyOrder`, `JsonRawValue`, `JsonSubTypes`, `JsonUnwrapped`, and `JsonValue`. `JsonType`
+cannot be added or removed because it controls build-time generation rather than the JSON schema.
+
+A source annotation replaces the target annotation of the same type on the matched declaration.
+The complete annotation is replaced, so omitted members use their declared defaults instead of
+inheriting values from the target annotation. Other annotation types on that target declaration
+remain effective.
+
+Use `JsonMixinRemove` to make selected target annotations ineffective:
+
+```java
+import org.apache.fory.json.annotation.JsonMixin;
+import org.apache.fory.json.annotation.JsonMixinRemove;
+import org.apache.fory.json.annotation.JsonRawValue;
+
+@JsonMixin(target = ThirdPartyMessage.class)
+abstract class QuotedMessageMixin {
+ @JsonMixinRemove(JsonRawValue.class)
+ String body;
+}
+```
+
+Removal affects only the matched declaration in the exact-target configuration. Removing
+`JsonRawValue` restores ordinary quoted String output; removing `JsonBase64` restores the ordinary
+`byte[]` representation; removing `JsonUnwrapped` restores a nested object property. Type-level
+removal can mask inherited `JsonCodec` or `JsonPropertyOrder` declarations for the exact target.
+Removing an absent annotation is harmless, but the selector must still match exactly one target
+declaration. A source cannot both declare and remove the same annotation type on one declaration.
+
+Only one source is enabled for an exact target in a built runtime. Registering a different source
+for the same target replaces the earlier registration, while registering the same source again is
+idempotent. `build()` snapshots the current last-registration-wins mapping; a later registration on
+the builder does not change a previously built `ForyJson`. A source with no mapping annotations is
+a no-op; registering it after another source for the same target clears the earlier overlay for
+subsequent builds.
+
+A `JsonCodec` supplied by a Mixin is the target's effective annotation and follows the ordinary
+codec precedence below. In particular, an exact `registerCodec` registration wins over a type-level
+Mixin codec, while a type-level Mixin codec wins over the built-in mapping for that target.
+
+Records use their existing field, accessor, and canonical-constructor parameter declarations. A
+Mixin does not introduce a separate record-component model. Use source selectors for those real
+declarations and keep repeated annotations consistent as required by normal record property
+mapping.
+
+On Android and GraalVM Native Image, compile non-empty Mixin sources with the Fory annotation
+processor so required generated operations and platform configuration are available. See
+[Android Support](android-support.md) and [GraalVM Support](graalvm-support.md).
+
### `JsonProperty`
An annotation on a field, getter, or setter configures the complete merged logical property:
@@ -1026,13 +1116,13 @@ The first `JsonAnySetter` parameter is the String property name. Its second para
Fory resolves each current value in this order:
-| Priority | Source |
-| -------: | ----------------------------------------- |
-| 1 | Current property or parameter `JsonCodec` |
-| 2 | Exact `registerCodec` registration |
-| 3 | Direct type `JsonCodec` declaration |
-| 4 | Inherited type declaration |
-| 5 | Built-in or default JSON mapping |
+| Priority | Source |
+| -------: | ------------------------------------------------- |
+| 1 | Current property or parameter `JsonCodec` |
+| 2 | Exact `registerCodec` registration |
+| 3 | Exact-target type `JsonCodec` after Mixin overlay |
+| 4 | Inherited-frontier type `JsonCodec` declaration |
+| 5 | Built-in or default JSON mapping |
One logical property may expose the annotation from its field, getter, setter parameter, creator
parameter, or record propagation. Repeated configurations must be identical; Fory does not merge
@@ -1059,9 +1149,10 @@ type-declaration codec is used for a more specific target, every decoded value m
assignable to that target.
The annotation has the same FIELD, METHOD, and PARAMETER behavior on the JVM, Android, and GraalVM
-Native Image. Ordinary Android classes may omit `JsonType` and provide equivalent exact rules;
-Android-desugared Records, including `JsonValue` Records, require `JsonType` and the processor.
-GraalVM object models follow the `JsonType` workflow in
+Native Image. Ordinary Android classes may omit `JsonType` and provide equivalent exact rules.
+Android-desugared Records, including `JsonValue` Records, require processor-generated operations
+from either a direct `JsonType` declaration or a compiled exact `JsonMixin` pair. GraalVM object
+models follow the build-time workflow in
[GraalVM Support](graalvm-support.md).
## Type validation and untrusted input
diff --git a/integration_tests/android_tests/README.md b/integration_tests/android_tests/README.md
index cb1a30473..a35d69708 100644
--- a/integration_tests/android_tests/README.md
+++ b/integration_tests/android_tests/README.md
@@ -5,8 +5,10 @@ This project runs Android API 26+ instrumented tests for Java `fory-core` and
suite. API 36 runs the release-minified suite. Release coverage verifies static
serializers, processor-generated Fory JSON execution for mutable classes,
`JsonCreator` classes, object-mapped and `JsonValue` desugared Records, generated
-retention rules, and equivalent application-authored exact rules for
-unannotated ordinary classes.
+retention rules, generated operations for the exact target-Mixin pair, and equivalent application-authored
+exact rules for unannotated ordinary classes. Mixin coverage
+registers the source at runtime after R8 minification so broad application keep
+rules cannot hide missing processor output.
The tests consume `org.apache.fory:fory-core:1.4.0-SNAPSHOT`,
`org.apache.fory:fory-json:1.4.0-SNAPSHOT`, and
diff --git a/integration_tests/android_tests/proguard-rules.pro b/integration_tests/android_tests/proguard-rules.pro
index 26ba0e40a..80115ad83 100644
--- a/integration_tests/android_tests/proguard-rules.pro
+++ b/integration_tests/android_tests/proguard-rules.pro
@@ -16,6 +16,7 @@
public static void manualCodecs();
public static void generatedCodecs();
public static void generatedUnwrapped();
+ public static void generatedMixin();
}
# Equivalent user-authored rules for models that deliberately omit @JsonType.
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 6c72d3d7b..ff713689a 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
@@ -70,6 +70,11 @@ public class ForyAndroidInstrumentedTest {
AndroidJsonScenarios.generatedUnwrapped();
}
+ @Test
+ public void generatedJsonMixin() {
+ AndroidJsonScenarios.generatedMixin();
+ }
+
@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 4f73215ce..5b0499951 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
@@ -25,9 +25,12 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
import org.apache.fory.json.ForyJson;
import org.apache.fory.json.annotation.JsonCreator;
+import org.apache.fory.json.annotation.JsonMixin;
+import org.apache.fory.json.annotation.JsonProperty;
import org.apache.fory.json.annotation.JsonPropertyOrder;
import org.apache.fory.json.annotation.JsonType;
import org.apache.fory.json.annotation.JsonUnwrapped;
+import org.apache.fory.json.annotation.JsonValue;
/** Android acceptance scenarios for reflection, declaration codecs, and R8 retention. */
public final class AndroidJsonScenarios {
@@ -234,6 +237,55 @@ public final class AndroidJsonScenarios {
checkEquals(33, decodedRecord.child().rank());
}
+ public static void generatedMixin() {
+ GeneratedJsonMixinTarget value =
+ GeneratedJsonMixinTarget.create(
+ 34, new GeneratedJsonMixinTarget.Address("Hangzhou", 310000));
+ String direct = ForyJson.builder().build().toJson(value);
+ check(direct.contains("\"id\":34"));
+ check(direct.contains("\"address\":{"));
+
+ ForyJson json = ForyJson.builder().registerMixin(GeneratedJsonMixin.class).build();
+ String encoded = json.toJson(value);
+ checkEquals("{\"user_id\":34,\"address_city\":\"Hangzhou\",\"address_zip\":310000}", encoded);
+ GeneratedJsonMixinTarget decoded = json.fromJson(encoded, GeneratedJsonMixinTarget.class);
+ checkEquals(34, decoded.getId());
+ checkEquals("Hangzhou", decoded.getAddress().city);
+ checkEquals(310000, decoded.getAddress().zip);
+
+ generatedMixinRecord();
+ generatedMixinValue();
+ generatedMixinValueRecord();
+ }
+
+ private static void generatedMixinRecord() {
+ ForyJson json =
+ ForyJson.builder().registerMixin(GeneratedJsonMixinRecordAnnotations.class).build();
+ String encoded = json.toJson(new GeneratedJsonMixinRecord(35, "record-mixin"));
+ checkEquals("{\"user_id\":35,\"display_name\":\"record-mixin\"}", encoded);
+ GeneratedJsonMixinRecord decoded = json.fromJson(encoded, GeneratedJsonMixinRecord.class);
+ checkEquals(35, decoded.id());
+ checkEquals("record-mixin", decoded.name());
+ }
+
+ private static void generatedMixinValue() {
+ ForyJson json = ForyJson.builder().registerMixin(GeneratedJsonMixinValue.class).build();
+ GeneratedJsonMixinValueTarget value = GeneratedJsonMixinValueTarget.create("value-mixin");
+ checkEquals("\"value-mixin\"", json.toJson(value));
+ GeneratedJsonMixinValueTarget decoded =
+ json.fromJson("\"decoded-mixin\"", GeneratedJsonMixinValueTarget.class);
+ checkEquals("decoded-mixin", decoded.getValue());
+ }
+
+ private static void generatedMixinValueRecord() {
+ ForyJson json =
+ ForyJson.builder().registerMixin(GeneratedJsonMixinValueRecordAnnotations.class).build();
+ checkEquals("\"record-value\"", json.toJson(new GeneratedJsonMixinValueRecord("record-value")));
+ GeneratedJsonMixinValueRecord decoded =
+ json.fromJson("\"decoded-record\"", GeneratedJsonMixinValueRecord.class);
+ checkEquals("decoded-record", decoded.value());
+ }
+
@JsonType
@JsonPropertyOrder({"id", "child"})
public static final class UnwrappedParent {
@@ -269,6 +321,113 @@ public final class AndroidJsonScenarios {
@JsonType
public record UnwrappedRecordChild(String name, int rank) {}
+ @JsonMixin(target = GeneratedJsonMixinTarget.class)
+ @JsonPropertyOrder({"id", "address"})
+ public interface GeneratedJsonMixin {
+ @JsonProperty("user_id")
+ int getId();
+
+ @JsonUnwrapped(prefix = "address_")
+ GeneratedJsonMixinTarget.Address getAddress();
+
+ @JsonCreator({"id", "address"})
+ GeneratedJsonMixinTarget create(int id, GeneratedJsonMixinTarget.Address address);
+ }
+
+ @JsonType
+ public static final class GeneratedJsonMixinTarget {
+ private final int id;
+ private final Address address;
+
+ private GeneratedJsonMixinTarget(int id, Address address) {
+ this.id = id;
+ this.address = address;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public Address getAddress() {
+ return address;
+ }
+
+ public static GeneratedJsonMixinTarget create(int id, Address address) {
+ return new GeneratedJsonMixinTarget(id, address);
+ }
+
+ public static final class Address {
+ public String city;
+ public int zip;
+
+ public Address() {}
+
+ public Address(String city, int zip) {
+ this.city = city;
+ this.zip = zip;
+ }
+ }
+ }
+
+ public record GeneratedJsonMixinRecord(int id, String name) {}
+
+ @JsonMixin(target = GeneratedJsonMixinRecord.class)
+ @JsonPropertyOrder({"id", "name"})
+ public abstract static class GeneratedJsonMixinRecordAnnotations {
+ @JsonProperty("user_id")
+ int id;
+
+ @JsonProperty("display_name")
+ String name;
+
+ @JsonProperty("user_id")
+ abstract int id();
+
+ @JsonProperty("display_name")
+ abstract String name();
+
+ GeneratedJsonMixinRecordAnnotations(
+ @JsonProperty("user_id") int id, @JsonProperty("display_name") String name) {}
+ }
+
+ @JsonMixin(target = GeneratedJsonMixinValueTarget.class)
+ public interface GeneratedJsonMixinValue {
+ @JsonValue
+ String getValue();
+
+ @JsonCreator
+ GeneratedJsonMixinValueTarget create(String value);
+ }
+
+ public static final class GeneratedJsonMixinValueTarget {
+ private final String value;
+
+ private GeneratedJsonMixinValueTarget(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public static GeneratedJsonMixinValueTarget create(String value) {
+ return new GeneratedJsonMixinValueTarget(value);
+ }
+ }
+
+ public record GeneratedJsonMixinValueRecord(String value) {}
+
+ @JsonMixin(target = GeneratedJsonMixinValueRecord.class)
+ public abstract static class GeneratedJsonMixinValueRecordAnnotations {
+ @JsonValue String value;
+
+ @JsonValue
+ abstract String value();
+
+ @JsonCreator
+ GeneratedJsonMixinValueRecordAnnotations(String value) {}
+ }
+
private static void check(boolean condition) {
if (!condition) {
throw new AssertionError("check failed");
diff --git a/integration_tests/graalvm_tests/README.md b/integration_tests/graalvm_tests/README.md
index 912bb1f1a..3192ebdc6 100644
--- a/integration_tests/graalvm_tests/README.md
+++ b/integration_tests/graalvm_tests/README.md
@@ -1,6 +1,10 @@
-# Graalvm native image Tests
+# GraalVM Native Image Tests
-Examples and tests for Fory serialization in graalvm native image
+Examples and tests for Fory serialization in GraalVM Native Image. The Fory JSON
+entry point covers direct `JsonType` models and runtime registration of exact
+`JsonMixin` target/source mappings. Native-image hosted analysis resolves each mapping and registers
+its generated factory when present. The built executables then execute direct and Mixin mappings at
+runtime; the module-path run verifies the same factories through JPMS.
## Test
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 a81be09d1..4f634d4e9 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
@@ -42,7 +42,9 @@ import org.apache.fory.json.annotation.JsonAnyProperty;
import org.apache.fory.json.annotation.JsonBase64;
import org.apache.fory.json.annotation.JsonCodec;
import org.apache.fory.json.annotation.JsonCreator;
+import org.apache.fory.json.annotation.JsonMixin;
import org.apache.fory.json.annotation.JsonProperty;
+import org.apache.fory.json.annotation.JsonPropertyOrder;
import org.apache.fory.json.annotation.JsonRawValue;
import org.apache.fory.json.annotation.JsonSubTypes;
import org.apache.fory.json.annotation.JsonType;
@@ -70,6 +72,11 @@ public final class ForyJsonExample {
testContainerRoots();
testGenericProperties();
testUnwrapped();
+ testMixin();
+ testMixinValue();
+ testMixinValueRecord();
+ testMixinEnumValue();
+ testMixinCodec();
testBigDecimal();
testSqlTypes();
testClosedPackage();
@@ -83,6 +90,65 @@ public final class ForyJsonExample {
Preconditions.checkArgument(json.fromJson(encoded, ClosedJsonRecord.class).equals(value));
}
+ private static void testMixin() {
+ JsonMixinTarget value =
+ JsonMixinTarget.create(18, new JsonMixinTarget.Address("Hangzhou", 310000));
+ String direct = ForyJson.builder().build().toJson(value);
+ Preconditions.checkArgument(direct.contains("\"id\":18"));
+ Preconditions.checkArgument(direct.contains("\"address\":{"));
+
+ ForyJson json = ForyJson.builder().registerMixin(JsonMixinModel.class).build();
+ String encoded = json.toJson(value);
+ Preconditions.checkArgument(
+ encoded.equals("{\"user_id\":18,\"address_city\":\"Hangzhou\",\"address_zip\":310000}"));
+ JsonMixinTarget decoded = json.fromJson(encoded, JsonMixinTarget.class);
+ Preconditions.checkArgument(decoded.getId() == 18);
+ Preconditions.checkArgument(decoded.getAddress().city.equals("Hangzhou"));
+ Preconditions.checkArgument(decoded.getAddress().zip == 310000);
+ }
+
+ private static void testMixinValue() {
+ ForyJson json = ForyJson.builder().registerMixin(JsonMixinValueModel.class).build();
+ JsonMixinValueTarget value = JsonMixinValueTarget.create("value-mixin");
+ Preconditions.checkArgument(json.toJson(value).equals("\"value-mixin\""));
+ JsonMixinValueTarget decoded = json.fromJson("\"decoded-mixin\"", JsonMixinValueTarget.class);
+ Preconditions.checkArgument(decoded.getValue().equals("decoded-mixin"));
+ }
+
+ private static void testMixinValueRecord() {
+ ForyJson json = ForyJson.builder().registerMixin(JsonMixinValueRecordModel.class).build();
+ Preconditions.checkArgument(
+ json.toJson(new JsonMixinValueRecord("record-value")).equals("\"record-value\""));
+ JsonMixinValueRecord decoded = json.fromJson("\"decoded-record\"", JsonMixinValueRecord.class);
+ Preconditions.checkArgument(decoded.value().equals("decoded-record"));
+ }
+
+ private static void testMixinEnumValue() {
+ ForyJson json = ForyJson.builder().registerMixin(JsonMixinEnumValueModel.class).build();
+ Preconditions.checkArgument(json.toJson(JsonMixinEnumValueTarget.READY).equals("\"ready\""));
+ Preconditions.checkArgument(
+ json.fromJson("\"done\"", JsonMixinEnumValueTarget.class) == JsonMixinEnumValueTarget.DONE);
+ }
+
+ private static void testMixinCodec() {
+ ForyJson json = ForyJson.builder().registerMixin(JsonMixinCodecModel.class).build();
+ JsonMixinCodecTarget value = new JsonMixinCodecTarget("mixin-codec");
+ Preconditions.checkArgument(json.toJson(value).equals("\"string:mixin-codec\""));
+ JsonMixinCodecTarget decoded =
+ json.fromJson("\"decoded-mixin-codec\"", JsonMixinCodecTarget.class);
+ checkStringRead(decoded.text, "decoded-mixin-codec");
+
+ ForyJson inherited =
+ ForyJson.builder().registerMixin(JsonMixinInheritedCodecModel.class).build();
+ JsonMixinInheritedCodecTarget inheritedValue =
+ new JsonMixinInheritedCodecTarget("inherited-codec");
+ Preconditions.checkArgument(
+ inherited.toJson(inheritedValue).equals("\"string:inherited-codec\""));
+ JsonMixinInheritedCodecTarget inheritedDecoded =
+ inherited.fromJson("\"decoded-inherited-codec\"", JsonMixinInheritedCodecTarget.class);
+ checkStringRead(inheritedDecoded.text, "decoded-inherited-codec");
+ }
+
private static void testModels() {
ForyJson json = ForyJson.builder().build();
Model value = new Model();
@@ -753,4 +819,197 @@ public final class ForyJsonExample {
public Time time;
public Timestamp timestamp;
}
+
+ @JsonMixin(target = JsonMixinTarget.class)
+ @JsonPropertyOrder({"id", "address"})
+ public interface JsonMixinModel {
+ @JsonProperty("user_id")
+ int getId();
+
+ @JsonUnwrapped(prefix = "address_")
+ JsonMixinTarget.Address getAddress();
+
+ @JsonCreator({"id", "address"})
+ JsonMixinTarget create(int id, JsonMixinTarget.Address address);
+ }
+
+ @JsonType
+ public static final class JsonMixinTarget {
+ private final int id;
+ private final Address address;
+
+ private JsonMixinTarget(int id, Address address) {
+ this.id = id;
+ this.address = address;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public Address getAddress() {
+ return address;
+ }
+
+ public static JsonMixinTarget create(int id, Address address) {
+ return new JsonMixinTarget(id, address);
+ }
+
+ public static final class Address {
+ public String city;
+ public int zip;
+
+ public Address() {}
+
+ public Address(String city, int zip) {
+ this.city = city;
+ this.zip = zip;
+ }
+ }
+ }
+
+ @JsonMixin(target = JsonMixinValueTarget.class)
+ public interface JsonMixinValueModel {
+ @JsonValue
+ String getValue();
+
+ @JsonCreator
+ JsonMixinValueTarget create(String value);
+ }
+
+ public static final class JsonMixinValueTarget {
+ private final String value;
+
+ private JsonMixinValueTarget(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public static JsonMixinValueTarget create(String value) {
+ return new JsonMixinValueTarget(value);
+ }
+ }
+
+ public record JsonMixinValueRecord(String value) {}
+
+ @JsonMixin(target = JsonMixinValueRecord.class)
+ public abstract static class JsonMixinValueRecordModel {
+ @JsonValue String value;
+
+ @JsonValue
+ abstract String value();
+
+ @JsonCreator
+ JsonMixinValueRecordModel(String value) {}
+ }
+
+ public enum JsonMixinEnumValueTarget {
+ READY("ready"),
+ DONE("done");
+
+ private final String value;
+
+ JsonMixinEnumValueTarget(String value) {
+ this.value = value;
+ }
+
+ @JsonValue
+ public String value() {
+ return value;
+ }
+
+ public static JsonMixinEnumValueTarget fromValue(String value) {
+ for (JsonMixinEnumValueTarget candidate : values()) {
+ if (candidate.value.equals(value)) {
+ return candidate;
+ }
+ }
+ throw new IllegalArgumentException(value);
+ }
+ }
+
+ @JsonMixin(target = JsonMixinEnumValueTarget.class)
+ public interface JsonMixinEnumValueModel {
+ @JsonCreator
+ JsonMixinEnumValueTarget fromValue(String value);
+ }
+
+ @JsonMixin(target = JsonMixinCodecTarget.class)
+ @JsonCodec(JsonMixinTargetCodec.class)
+ public interface JsonMixinCodecModel {}
+
+ public static final class JsonMixinCodecTarget implements TextValue {
+ @JsonCodec(UnreachableFieldCodec.class)
+ public CodecValue ignored;
+
+ private final String text;
+
+ JsonMixinCodecTarget(String text) {
+ this.text = text;
+ }
+
+ @Override
+ public String text() {
+ return text;
+ }
+ }
+
+ public static final class JsonMixinTargetCodec extends TextCodec<JsonMixinCodecTarget> {
+ public JsonMixinTargetCodec() {}
+
+ @Override
+ protected JsonMixinCodecTarget create(String text) {
+ return new JsonMixinCodecTarget(text);
+ }
+ }
+
+ public static final class UnreachableFieldCodec extends TextCodec<CodecValue> {
+ private UnreachableFieldCodec() {}
+
+ @Override
+ protected CodecValue create(String text) {
+ return new CodecValue(text);
+ }
+ }
+
+ @JsonCodec(JsonMixinInheritedTargetCodec.class)
+ public interface JsonMixinInheritedCodecContract {}
+
+ @JsonMixin(target = JsonMixinInheritedCodecTarget.class)
+ public interface JsonMixinInheritedCodecModel {
+ @JsonValue
+ @JsonCodec(UnreachableFieldCodec.class)
+ String value();
+ }
+
+ public static final class JsonMixinInheritedCodecTarget
+ implements TextValue, JsonMixinInheritedCodecContract {
+ private final String text;
+
+ JsonMixinInheritedCodecTarget(String text) {
+ this.text = text;
+ }
+
+ public String value() {
+ return text;
+ }
+
+ @Override
+ public String text() {
+ return text;
+ }
+ }
+
+ public static final class JsonMixinInheritedTargetCodec
+ extends TextCodec<JsonMixinInheritedCodecTarget> {
+ public JsonMixinInheritedTargetCodec() {}
+
+ @Override
+ protected JsonMixinInheritedCodecTarget create(String text) {
+ return new JsonMixinInheritedCodecTarget(text);
+ }
+ }
}
diff --git a/java/fory-annotation-processor/README.md b/java/fory-annotation-processor/README.md
index 335adafc3..15bcc2473 100644
--- a/java/fory-annotation-processor/README.md
+++ b/java/fory-annotation-processor/README.md
@@ -1,23 +1,27 @@
# Fory Annotation Processor
`fory-annotation-processor` generates static serializers for Java classes annotated with
-`@ForyStruct`. For concrete Fory JSON object models annotated with `@JsonType`, and for directly
-annotated `JsonValue` Records, it generates a `_ForyJsonCodec` companion with direct member and
-creator operations together with exact Android R8 rules. The generated rules retain effective
-`@JsonValue`, `@JsonRawValue`, and `@JsonBase64` members, their runtime annotations, and selected
-codec constructors. The outputs are generated by javac during the application build.
+`@ForyStruct`. For Fory JSON it processes direct `@JsonType` models and
+`@JsonMixin(target = ...)` declarations. Direct models receive their existing type-owned JSON
+companion when required. A non-empty Mixin receives exact platform configuration and a
+pair-specific companion when generated target operations are available. Runtime codec resolution,
+including registered and built-in codecs, still decides whether those operations are used. The
+generated rules retain the complete effective annotation surface, matched target declarations,
+generic endpoints, subtype and unwrapped models, and selected codec constructors. An empty Mixin
+produces no output. All outputs are generated by javac during the application build.
Use this processor for:
- Android applications.
-- ordinary JVM applications using `ForyBuilder#withCodegen(false)`.
+- ordinary JVM applications using `ForyJsonBuilder#withCodegen(false)`.
- Android model classes that use Fory type-use annotations such as `@Ref`, `@UInt8Type`, or
`@Float16Type`.
- Fory JSON object models that need direct member access, Android Record support, GraalVM metadata,
or automatic R8 rules.
-For GraalVM native images, use the processor for `@JsonType` JSON models and Fory's native-image
-build-time serializer generation for ordinary Fory serialization.
+For GraalVM native images, use the processor for every reachable `@JsonType` JSON model and
+`@JsonMixin` source, and use Fory's native-image build-time serializer generation for ordinary Fory
+serialization.
## Ownership
@@ -25,14 +29,28 @@ The processor is an opt-in build tool. Applications add it to their annotation-p
processor has no production dependency on `fory-core` or `fory-json`; generated sources compile
against the corresponding runtime artifact already used by the application.
+A Mixin source declares exactly one target. The processor may generate pair artifacts for multiple
+sources that name the same target because they are alternative runtime configurations. One
+`ForyJsonBuilder` enables one source per exact target, and a later registration replaces an earlier
+one before `build()` snapshots the mapping. The processor never merges multiple sources and never
+changes the direct companion path without a Mixin. A source must be named, must not be local or anonymous,
+and must not extend another source or implement interfaces, so there is no second
+annotation-precedence hierarchy.
+
+`JsonMixin` supports the Fory JSON mapping annotations. `JsonType` remains a direct
+build-time marker and cannot be added or removed through a Mixin. The processor does not duplicate
+the runtime's built-in codec selection.
+
For ordinary Fory JSON object models on Android, `@JsonType` is optional. A model without it can use
application-authored exact R8 rules and reflection. Android builds that need desugared Java Record
-construction use `@JsonType`, because the generated companion calls the canonical constructor and
+construction require processor-generated operations from either a direct `@JsonType` declaration
+or a compiled exact `@JsonMixin` pair, because generated code calls the canonical constructor and
component accessors directly. This includes a Record using a String `JsonValue` representation and
an annotated canonical constructor. `@JsonCodec` uses ordinary type, field, method, and parameter
annotations, so every supported codec member remains available through reflection with equivalent
rules. See
[`docs/guide/java/android-support.md`](../../docs/guide/java/android-support.md).
-For the full user-facing guide, see
-[`docs/guide/java/static-generated-serializers.md`](../../docs/guide/java/static-generated-serializers.md).
+For the full user-facing guides, see
+[`docs/guide/java/static-generated-serializers.md`](../../docs/guide/java/static-generated-serializers.md)
+and [`docs/guide/java/json-support.md`](../../docs/guide/java/json-support.md).
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 d0257dcba..795378a50 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
@@ -76,6 +76,8 @@ public final class ForyStructProcessor extends AbstractProcessor {
private static final String FORY_FIELD = annotationClass("ForyField");
private static final String FORY_STRUCT = annotationClass("ForyStruct");
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 IGNORE = annotationClass("Ignore");
private static final String INT32_TYPE = annotationClass("Int32Type");
private static final String INT64_TYPE = annotationClass("Int64Type");
@@ -103,6 +105,8 @@ public final class ForyStructProcessor extends AbstractProcessor {
annotations.add(FORY_STRUCT);
annotations.add(FORY_DEBUG);
annotations.add(JSON_TYPE);
+ annotations.add(JSON_MIXIN);
+ annotations.add(JSON_MIXIN_REMOVE);
return Collections.unmodifiableSet(annotations);
}
diff --git a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/GeneratedJsonCodecSourceWriter.java b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/GeneratedJsonCodecSourceWriter.java
index cfc7d5689..0d9a6032e 100644
--- a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/GeneratedJsonCodecSourceWriter.java
+++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/GeneratedJsonCodecSourceWriter.java
@@ -54,7 +54,7 @@ import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.JavaFileObject;
-/** Writes the direct JSON object operations owned by one {@code JsonType} model. */
+/** Writes direct target operations for one JSON model or exact target-Mixin pair. */
final class GeneratedJsonCodecSourceWriter {
private static final String JSON_PACKAGE = "org.apache.fory.json";
private static final String JSON_CODEC = JSON_PACKAGE + ".annotation.JsonCodec";
@@ -100,18 +100,41 @@ final class GeneratedJsonCodecSourceWriter {
}
Result write(TypeElement target) {
- if (!needsGeneratedCodec(target)) {
+ if (!needsGeneratedCodec(
+ target, null, elements.getPackageOf(target).getQualifiedName().toString())) {
return null;
}
- Model model = buildModel(target);
+ Model model = buildModel(target, null);
+ return writeSource(model, target);
+ }
+
+ Result writePair(JsonMixinAnnotations annotations) {
+ TypeElement target = annotations.target();
+ TypeElement mixin = annotations.source();
+ String packageName = elements.getPackageOf(mixin).getQualifiedName().toString();
+ Model model;
try {
- JavaFileObject file = filer.createSourceFile(model.qualifiedName, target);
+ if (!needsGeneratedCodec(target, annotations, packageName)) {
+ return null;
+ }
+ model = buildModel(target, annotations);
+ } catch (InvalidJsonTypeException ignored) {
+ // A runtime-registered or built-in codec can own this pair without generated object access.
+ // Runtime codec resolution decides whether the absent pair codec is an error.
+ return null;
+ }
+ return writeSource(model, mixin, target);
+ }
+
+ private Result writeSource(Model model, Element... originatingElements) {
+ try {
+ JavaFileObject file = filer.createSourceFile(model.qualifiedName, originatingElements);
try (Writer writer = file.openWriter()) {
writer.write(render(model));
}
} catch (IOException e) {
throw invalid(
- "Failed to write generated JSON codec " + model.qualifiedName + ": " + e, target);
+ "Failed to write generated JSON codec " + model.qualifiedName + ": " + e, model.target);
}
return new Result(
model.binaryName,
@@ -122,51 +145,56 @@ final class GeneratedJsonCodecSourceWriter {
model.creator != null && model.creator.record);
}
- private boolean needsGeneratedCodec(TypeElement target) {
+ private boolean needsGeneratedCodec(
+ TypeElement target, JsonMixinAnnotations annotations, String generatedPackage) {
boolean record = isRecord(target);
if (!(target.getKind() == ElementKind.CLASS || record)
|| target.getModifiers().contains(Modifier.ABSTRACT)
- || annotationMirror(target, JSON_SUB_TYPES) != null) {
+ || annotationMirror(annotations, target, JSON_SUB_TYPES) != null) {
return false;
}
- if (hasCompleteTypeCodec(target)
- || !record && hasEffectiveJsonValue(target)
- || isObjectCodecExcluded(target)) {
+ // Built-in codec selection belongs to the runtime. Applying the direct @JsonType exclusion
+ // inventory to a Mixin would make the processor choose runtime representation.
+ if (hasCompleteTypeCodec(target, annotations)
+ || !record && hasJsonValueDeclaration(target, annotations)
+ || annotations == null && isObjectCodecExcluded(target)) {
return false;
}
- if (!isNameable(target)) {
- throw invalid("@JsonType model is not accessible to generated JSON code", target);
+ if (!isNameable(target.asType(), generatedPackage)) {
+ throw invalid(
+ (annotations == null ? "@JsonType model" : "@JsonMixin target")
+ + " is not accessible to generated JSON code",
+ target);
}
return true;
}
- private boolean hasEffectiveJsonValue(TypeElement target) {
+ private boolean hasJsonValueDeclaration(TypeElement target, JsonMixinAnnotations annotations) {
for (TypeElement owner : classHierarchy(target)) {
for (VariableElement field : ElementFilter.fieldsIn(owner.getEnclosedElements())) {
- if (annotationMirror(field, JSON_VALUE) != null) {
+ if (annotationMirror(annotations, field, JSON_VALUE) != null) {
return true;
}
}
}
for (ExecutableElement method : effectiveMethods(target)) {
if (method.getModifiers().contains(Modifier.PUBLIC)
- && annotationMirror(method, JSON_VALUE) != null) {
+ && annotationMirror(annotations, method, JSON_VALUE) != null) {
return true;
}
}
return false;
}
- private boolean hasCompleteTypeCodec(TypeElement target) {
- AnnotationMirror direct = annotationMirror(target, JSON_CODEC);
- if (direct != null) {
- return selectsValueCodec(direct);
+ boolean hasCompleteTypeCodec(TypeElement target, JsonMixinAnnotations annotations) {
+ if (hasDirectTypeCodec(target, annotations)) {
+ return true;
}
List<TypeElement> declarations = allDeclarations(target);
List<TypeElement> candidates = new ArrayList<>();
for (int i = 1; i < declarations.size(); i++) {
TypeElement declaration = declarations.get(i);
- if (annotationMirror(declaration, JSON_CODEC) != null) {
+ if (annotationMirror(annotations, declaration, JSON_CODEC) != null) {
candidates.add(declaration);
}
}
@@ -180,13 +208,18 @@ final class GeneratedJsonCodecSourceWriter {
break;
}
}
- if (!dominated && selectsValueCodec(annotationMirror(candidate, JSON_CODEC))) {
+ if (!dominated && selectsValueCodec(annotationMirror(annotations, candidate, JSON_CODEC))) {
return true;
}
}
return false;
}
+ boolean hasDirectTypeCodec(TypeElement target, JsonMixinAnnotations annotations) {
+ AnnotationMirror direct = annotationMirror(annotations, target, JSON_CODEC);
+ return direct != null && selectsValueCodec(direct);
+ }
+
private boolean selectsValueCodec(AnnotationMirror annotation) {
AnnotationValue value = annotationValue(annotation, "value");
if (value == null || !(value.getValue() instanceof TypeMirror)) {
@@ -216,12 +249,21 @@ final class GeneratedJsonCodecSourceWriter {
return false;
}
- private Model buildModel(TypeElement target) {
- String packageName = elements.getPackageOf(target).getQualifiedName().toString();
+ private Model buildModel(TypeElement target, JsonMixinAnnotations annotations) {
+ TypeElement mixin = annotations == null ? null : annotations.source();
+ String packageName =
+ elements.getPackageOf(mixin == null ? target : mixin).getQualifiedName().toString();
String targetBinaryName = elements.getBinaryName(target).toString();
- String binarySimpleName =
- targetBinaryName.substring(packageName.isEmpty() ? 0 : packageName.length() + 1);
- String simpleName = GeneratedTypeNames.escapeBinarySimpleName(binarySimpleName) + SUFFIX;
+ String mixinBinaryName = mixin == null ? null : elements.getBinaryName(mixin).toString();
+ String simpleName;
+ if (mixin == null) {
+ String binarySimpleName =
+ targetBinaryName.substring(packageName.isEmpty() ? 0 : packageName.length() + 1);
+ simpleName = GeneratedTypeNames.escapeBinarySimpleName(binarySimpleName) + SUFFIX;
+ } else {
+ simpleName =
+ GeneratedTypeNames.jsonMixinSimpleName(mixinBinaryName, targetBinaryName) + SUFFIX;
+ }
Model model =
new Model(
target,
@@ -230,7 +272,8 @@ final class GeneratedJsonCodecSourceWriter {
simpleName,
packageName.isEmpty() ? simpleName : packageName + "." + simpleName,
packageName.isEmpty() ? simpleName : packageName + "." + simpleName,
- sourceType(target.asType()));
+ sourceType(target.asType()),
+ annotations);
collectFieldAccessors(model);
collectMethodAccessors(model);
model.anySetter = findAnySetter(model);
@@ -287,7 +330,7 @@ final class GeneratedJsonCodecSourceWriter {
for (ExecutableElement method : effectiveMethods(model.target)) {
if (!method.getModifiers().contains(Modifier.PUBLIC)
|| method.getModifiers().contains(Modifier.STATIC)
- || annotationMirror(method, JSON_ANY_SETTER) != null
+ || annotationMirror(model.annotations, method, JSON_ANY_SETTER) != null
|| method.isVarArgs()
|| !method.getTypeParameters().isEmpty()) {
continue;
@@ -299,7 +342,7 @@ final class GeneratedJsonCodecSourceWriter {
ExecutableType resolved =
(ExecutableType) types.asMemberOf((DeclaredType) model.target.asType(), method);
String key = methodKey(owner, method);
- if (isGetter(method, resolved)
+ if (isGetter(model, method, resolved)
&& isNameable(types.erasure(resolved.getReturnType()), model.packageName)
&& seen.add(key)) {
model.accessors.add(
@@ -312,7 +355,7 @@ final class GeneratedJsonCodecSourceWriter {
model.addR8Member(
elements.getBinaryName(owner).toString(),
binaryType(method.getReturnType()) + " " + method.getSimpleName() + "();");
- } else if (isSetter(method, resolved)
+ } else if (isSetter(model, method, resolved)
&& isNameable(types.erasure(resolved.getParameterTypes().get(0)), model.packageName)
&& isNameable(types.erasure(method.getParameters().get(0).asType()), model.packageName)
&& seen.add(key)) {
@@ -361,7 +404,7 @@ final class GeneratedJsonCodecSourceWriter {
private AnySetter findAnySetter(Model model) {
ExecutableElement selected = null;
for (ExecutableElement method : effectiveMethods(model.target)) {
- if (annotationMirror(method, JSON_ANY_SETTER) == null) {
+ if (annotationMirror(model.annotations, method, JSON_ANY_SETTER) == null) {
continue;
}
if (selected != null) {
@@ -382,12 +425,14 @@ final class GeneratedJsonCodecSourceWriter {
|| resolved.getReturnType().getKind() != TypeKind.VOID
|| resolved.getParameterTypes().size() != 2
|| !binaryType(resolved.getParameterTypes().get(0)).equals("java.lang.String")
- || !binaryType(selected.getParameters().get(0).asType()).equals("java.lang.String")
- || !isNameable(owner.asType(), model.packageName)
+ || !binaryType(selected.getParameters().get(0).asType()).equals("java.lang.String")) {
+ // Runtime metadata validation owns the diagnostic for malformed annotations.
+ return null;
+ }
+ if (!isNameable(owner.asType(), model.packageName)
|| !isNameable(types.erasure(resolved.getParameterTypes().get(1)), model.packageName)
|| !isNameable(
types.erasure(selected.getParameters().get(1).asType()), model.packageName)) {
- // Runtime metadata validation owns the diagnostic for malformed annotations.
return null;
}
return new AnySetter(
@@ -416,28 +461,28 @@ final class GeneratedJsonCodecSourceWriter {
kinds.add(type.getKind());
}
for (ExecutableElement method : ElementFilter.methodsIn(model.target.getEnclosedElements())) {
- if (annotationMirror(method, JSON_CREATOR) != null) {
+ if (annotationMirror(model.annotations, method, JSON_CREATOR) != null) {
throw invalid("Records cannot declare @JsonCreator", method);
}
}
- boolean valueRecord = hasEffectiveJsonValue(model.target);
+ boolean valueRecord = hasJsonValueDeclaration(model.target, model.annotations);
ExecutableElement canonicalConstructor = null;
for (ExecutableElement constructor :
ElementFilter.constructorsIn(model.target.getEnclosedElements())) {
- if (annotationMirror(constructor, JSON_CREATOR) != null
- && (!valueRecord || !isRecordValueCreator(constructor, components))) {
+ if (annotationMirror(model.annotations, constructor, JSON_CREATOR) != null
+ && (!valueRecord || !isRecordValueCreator(model, constructor, components))) {
throw invalid("Records cannot declare @JsonCreator", constructor);
}
if (isRecordConstructor(constructor, components)) {
canonicalConstructor = constructor;
} else {
- rejectRecordParameters(constructor);
+ rejectRecordParameters(model, constructor);
}
}
if (canonicalConstructor == null) {
throw invalid("Cannot find the canonical Record constructor", model.target);
}
- validateRecordParameters(model.target, components, canonicalConstructor);
+ validateRecordParameters(model, components, canonicalConstructor);
String declaration = "<init>(" + join(binaryTypes) + ");";
return new Creator(names, sourceTypes, kinds, null, true, declaration, false);
}
@@ -457,11 +502,11 @@ final class GeneratedJsonCodecSourceWriter {
return true;
}
- private void rejectRecordParameters(ExecutableElement constructor) {
+ private void rejectRecordParameters(Model model, ExecutableElement constructor) {
for (VariableElement parameter : constructor.getParameters()) {
- if (annotationMirror(parameter, JSON_CODEC) != null
- || annotationMirror(parameter, JSON_PROPERTY) != null
- || annotationMirror(parameter, JSON_UNWRAPPED) != null) {
+ if (annotationMirror(model.annotations, parameter, JSON_CODEC) != null
+ || annotationMirror(model.annotations, parameter, JSON_PROPERTY) != null
+ || annotationMirror(model.annotations, parameter, JSON_UNWRAPPED) != null) {
throw invalid(
"JSON property annotations are not supported on non-canonical Record constructor parameters",
parameter);
@@ -470,31 +515,33 @@ final class GeneratedJsonCodecSourceWriter {
}
private void validateRecordParameters(
- TypeElement target, List<? extends Element> components, ExecutableElement constructor) {
+ Model model, List<? extends Element> components, ExecutableElement constructor) {
List<? extends VariableElement> parameters = constructor.getParameters();
for (int i = 0; i < components.size(); i++) {
Element component = components.get(i);
- VariableElement field = findRecordField(target, component);
- ExecutableElement accessor = findRecordAccessor(target, component);
- validateRecordAnnotation(parameters.get(i), field, accessor, JSON_CODEC);
- validateRecordAnnotation(parameters.get(i), field, accessor, JSON_PROPERTY);
- validateRecordAnnotation(parameters.get(i), field, accessor, JSON_UNWRAPPED);
+ VariableElement field = findRecordField(model.target, component);
+ ExecutableElement accessor = findRecordAccessor(model.target, component);
+ validateRecordAnnotation(model, parameters.get(i), field, accessor, JSON_CODEC);
+ validateRecordAnnotation(model, parameters.get(i), field, accessor, JSON_PROPERTY);
+ validateRecordAnnotation(model, parameters.get(i), field, accessor, JSON_UNWRAPPED);
}
}
private void validateRecordAnnotation(
+ Model model,
VariableElement parameter,
VariableElement field,
ExecutableElement accessor,
String annotationName) {
- AnnotationMirror parameterAnnotation = annotationMirror(parameter, annotationName);
+ AnnotationMirror parameterAnnotation =
+ annotationMirror(model.annotations, parameter, annotationName);
if (parameterAnnotation == null) {
return;
}
AnnotationMirror fieldAnnotation =
- field == null ? null : annotationMirror(field, annotationName);
+ field == null ? null : annotationMirror(model.annotations, field, annotationName);
AnnotationMirror accessorAnnotation =
- accessor == null ? null : annotationMirror(accessor, annotationName);
+ accessor == null ? null : annotationMirror(model.annotations, accessor, annotationName);
if (sameAnnotation(parameterAnnotation, fieldAnnotation)
|| sameAnnotation(parameterAnnotation, accessorAnnotation)) {
return;
@@ -521,7 +568,7 @@ final class GeneratedJsonCodecSourceWriter {
}
private boolean isRecordValueCreator(
- ExecutableElement constructor, List<? extends Element> components) {
+ Model model, ExecutableElement constructor, List<? extends Element> components) {
if (!constructor.getModifiers().contains(Modifier.PUBLIC)
|| constructor.isVarArgs()
|| !constructor.getTypeParameters().isEmpty()
@@ -531,10 +578,11 @@ final class GeneratedJsonCodecSourceWriter {
|| !types.isSameType(
types.erasure(constructor.getParameters().get(0).asType()),
types.erasure(components.get(0).asType()))
- || annotationMirror(constructor.getParameters().get(0), JSON_PROPERTY) != null) {
+ || annotationMirror(model.annotations, constructor.getParameters().get(0), JSON_PROPERTY)
+ != null) {
return false;
}
- AnnotationMirror creator = annotationMirror(constructor, JSON_CREATOR);
+ AnnotationMirror creator = annotationMirror(model.annotations, constructor, JSON_CREATOR);
return stringArray(annotationValue(creator, "value")).isEmpty();
}
@@ -543,7 +591,7 @@ final class GeneratedJsonCodecSourceWriter {
boolean factory = false;
for (ExecutableElement constructor :
ElementFilter.constructorsIn(model.target.getEnclosedElements())) {
- if (annotationMirror(constructor, JSON_CREATOR) != null) {
+ if (annotationMirror(model.annotations, constructor, JSON_CREATOR) != null) {
if (creator != null) {
throw invalid("Exactly one @JsonCreator constructor or factory is allowed", constructor);
}
@@ -551,7 +599,7 @@ final class GeneratedJsonCodecSourceWriter {
}
}
for (ExecutableElement method : ElementFilter.methodsIn(model.target.getEnclosedElements())) {
- if (annotationMirror(method, JSON_CREATOR) != null) {
+ if (annotationMirror(model.annotations, method, JSON_CREATOR) != null) {
if (creator != null) {
throw invalid("Exactly one @JsonCreator constructor or factory is allowed", method);
}
@@ -563,7 +611,7 @@ final class GeneratedJsonCodecSourceWriter {
return null;
}
validateCreator(model, creator, factory);
- List<String> names = creatorParameterNames(creator);
+ List<String> names = creatorParameterNames(model, creator);
List<String> sourceTypes = new ArrayList<>();
List<String> binaryTypes = new ArrayList<>();
List<TypeKind> kinds = new ArrayList<>();
@@ -611,8 +659,8 @@ final class GeneratedJsonCodecSourceWriter {
}
}
- private List<String> creatorParameterNames(ExecutableElement creator) {
- AnnotationMirror annotation = annotationMirror(creator, JSON_CREATOR);
+ private List<String> creatorParameterNames(Model model, ExecutableElement creator) {
+ AnnotationMirror annotation = annotationMirror(model.annotations, creator, JSON_CREATOR);
AnnotationValue value = annotationValue(annotation, "value");
List<String> names = stringArray(value);
if (!names.isEmpty()) {
@@ -622,7 +670,7 @@ final class GeneratedJsonCodecSourceWriter {
Set<String> unique = new HashSet<>();
for (int i = 0; i < names.size(); i++) {
VariableElement parameter = creator.getParameters().get(i);
- if (annotationMirror(parameter, JSON_PROPERTY) != null) {
+ if (annotationMirror(model.annotations, parameter, JSON_PROPERTY) != null) {
throw invalid(
"Property-list @JsonCreator parameters cannot declare @JsonProperty", parameter);
}
@@ -636,7 +684,7 @@ final class GeneratedJsonCodecSourceWriter {
names = new ArrayList<>();
Set<String> unique = new HashSet<>();
for (VariableElement parameter : creator.getParameters()) {
- AnnotationMirror property = annotationMirror(parameter, JSON_PROPERTY);
+ AnnotationMirror property = annotationMirror(model.annotations, parameter, JSON_PROPERTY);
AnnotationValue propertyName = property == null ? null : annotationValue(property, "value");
String name = propertyName == null ? "" : String.valueOf(propertyName.getValue());
if (name.isEmpty() || !unique.add(name)) {
@@ -984,15 +1032,15 @@ final class GeneratedJsonCodecSourceWriter {
return result;
}
- private boolean isGetter(ExecutableElement method, ExecutableType resolved) {
+ private boolean isGetter(Model model, ExecutableElement method, ExecutableType resolved) {
if (!resolved.getParameterTypes().isEmpty()
|| resolved.getReturnType().getKind() == TypeKind.VOID
|| binaryType(resolved.getReturnType()).equals("java.lang.Class")) {
return false;
}
String name = method.getSimpleName().toString();
- return annotationMirror(method, JSON_PROPERTY) != null
- || annotationMirror(method, JSON_ANY_GETTER) != null
+ return annotationMirror(model.annotations, method, JSON_PROPERTY) != null
+ || annotationMirror(model.annotations, method, JSON_ANY_GETTER) != null
|| name.startsWith("get") && name.length() > 3
|| name.startsWith("is")
&& name.length() > 2
@@ -1000,14 +1048,14 @@ final class GeneratedJsonCodecSourceWriter {
|| binaryType(resolved.getReturnType()).equals("java.lang.Boolean"));
}
- private boolean isSetter(ExecutableElement method, ExecutableType resolved) {
+ private boolean isSetter(Model model, ExecutableElement method, ExecutableType resolved) {
if (resolved.getParameterTypes().size() != 1
|| resolved.getReturnType().getKind() != TypeKind.VOID
|| binaryType(resolved.getParameterTypes().get(0)).equals("java.lang.Class")) {
return false;
}
String name = method.getSimpleName().toString();
- return annotationMirror(method, JSON_PROPERTY) != null
+ return annotationMirror(model.annotations, method, JSON_PROPERTY) != null
|| name.startsWith("set") && name.length() > 3;
}
@@ -1172,6 +1220,13 @@ final class GeneratedJsonCodecSourceWriter {
return null;
}
+ private AnnotationMirror annotationMirror(
+ JsonMixinAnnotations annotations, Element element, String annotationName) {
+ return annotations == null
+ ? annotationMirror(element, annotationName)
+ : annotations.annotation(element, annotationName);
+ }
+
private AnnotationValue annotationValue(AnnotationMirror annotation, String name) {
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
elements.getElementValuesWithDefaults(annotation).entrySet()) {
@@ -1380,6 +1435,7 @@ final class GeneratedJsonCodecSourceWriter {
final String qualifiedName;
final String binaryName;
final String targetType;
+ final JsonMixinAnnotations annotations;
final List<Accessor> accessors = new ArrayList<>();
final List<MemberRule> r8Members = new ArrayList<>();
final Set<String> r8MemberKeys = new HashSet<>();
@@ -1393,7 +1449,8 @@ final class GeneratedJsonCodecSourceWriter {
String simpleName,
String qualifiedName,
String binaryName,
- String targetType) {
+ String targetType,
+ JsonMixinAnnotations annotations) {
this.target = target;
this.packageName = packageName;
this.targetBinaryName = targetBinaryName;
@@ -1401,6 +1458,7 @@ final class GeneratedJsonCodecSourceWriter {
this.qualifiedName = qualifiedName;
this.binaryName = binaryName;
this.targetType = targetType;
+ this.annotations = annotations;
}
void addR8Member(String ownerBinaryName, String declaration) {
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 12398eedd..157ad6b6d 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
@@ -31,6 +31,16 @@ final class GeneratedTypeNames {
return escape(binaryName, true);
}
+ static String jsonMixinSimpleName(String mixinBinaryName, String targetBinaryName) {
+ // Keep this pair name identical to JsonSharedRegistry.generatedMixinCodecBinaryName; the
+ // processor cannot depend on the runtime module that loads the generated class.
+ int packageSeparator = mixinBinaryName.lastIndexOf('.');
+ String mixinSimpleName = mixinBinaryName.substring(packageSeparator + 1);
+ return escapeBinarySimpleName(mixinSimpleName)
+ + "_ForyJsonMixin_"
+ + escapeBinarySimpleName(targetBinaryName);
+ }
+
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/JsonMixinAnnotations.java b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonMixinAnnotations.java
new file mode 100644
index 000000000..0c0d414e9
--- /dev/null
+++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonMixinAnnotations.java
@@ -0,0 +1,578 @@
+/*
+ * 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.lang.annotation.ElementType;
+import java.lang.annotation.Target;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.NestingKind;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.util.ElementFilter;
+import javax.lang.model.util.Elements;
+import javax.lang.model.util.Types;
+
+/** Resolves one Mixin source into an immutable effective-annotation table for its exact target. */
+final class JsonMixinAnnotations {
+ private static final String JSON_PACKAGE = "org.apache.fory.json";
+ private static final String JSON_MIXIN_REMOVE = JSON_PACKAGE + ".annotation.JsonMixinRemove";
+ private static final String JSON_TYPE = JSON_PACKAGE + ".annotation.JsonType";
+ private static final String JSON_ANY_GETTER = JSON_PACKAGE + ".annotation.JsonAnyGetter";
+ private static final String JSON_ANY_PROPERTY = JSON_PACKAGE + ".annotation.JsonAnyProperty";
+ private static final String JSON_ANY_SETTER = JSON_PACKAGE + ".annotation.JsonAnySetter";
+ private static final String JSON_BASE64 = JSON_PACKAGE + ".annotation.JsonBase64";
+ private static final String JSON_CODEC = JSON_PACKAGE + ".annotation.JsonCodec";
+ private static final String JSON_CREATOR = JSON_PACKAGE + ".annotation.JsonCreator";
+ private static final String JSON_IGNORE = JSON_PACKAGE + ".annotation.JsonIgnore";
+ private static final String JSON_PROPERTY = JSON_PACKAGE + ".annotation.JsonProperty";
+ private static final String JSON_PROPERTY_ORDER = JSON_PACKAGE + ".annotation.JsonPropertyOrder";
+ private static final String JSON_RAW_VALUE = JSON_PACKAGE + ".annotation.JsonRawValue";
+ private static final String JSON_SUB_TYPES = JSON_PACKAGE + ".annotation.JsonSubTypes";
+ private static final String JSON_UNWRAPPED = JSON_PACKAGE + ".annotation.JsonUnwrapped";
+ private static final String JSON_VALUE = JSON_PACKAGE + ".annotation.JsonValue";
+
+ private static final Set<String> MAPPING_ANNOTATIONS =
+ Collections.unmodifiableSet(
+ new LinkedHashSet<>(
+ Arrays.asList(
+ JSON_ANY_GETTER,
+ JSON_ANY_PROPERTY,
+ JSON_ANY_SETTER,
+ JSON_BASE64,
+ JSON_CODEC,
+ JSON_CREATOR,
+ JSON_IGNORE,
+ JSON_PROPERTY,
+ JSON_PROPERTY_ORDER,
+ JSON_RAW_VALUE,
+ JSON_SUB_TYPES,
+ JSON_UNWRAPPED,
+ JSON_VALUE)));
+
+ private final TypeElement target;
+ private final TypeElement source;
+ private final Map<Element, Overlay> overlays;
+
+ private JsonMixinAnnotations(
+ TypeElement target, TypeElement source, Map<Element, Overlay> overlays) {
+ this.target = target;
+ this.source = source;
+ this.overlays = overlays;
+ }
+
+ static JsonMixinAnnotations resolve(
+ Elements elements, Types types, TypeElement target, TypeElement source) {
+ validateTypes(target, source);
+ Map<Element, Overlay> overlays = new IdentityHashMap<>();
+ Overlay typeOverlay = overlay(source);
+ if (typeOverlay != null) {
+ overlays.put(target, typeOverlay);
+ }
+ for (VariableElement sourceField : ElementFilter.fieldsIn(source.getEnclosedElements())) {
+ Overlay overlay = overlay(sourceField);
+ if (overlay != null) {
+ if (sourceField.getModifiers().contains(Modifier.STATIC)) {
+ throw invalid("@JsonMixin field selector must be an instance field", sourceField);
+ }
+ overlays.put(matchField(elements, types, target, source, sourceField), overlay);
+ }
+ }
+ for (ExecutableElement sourceMethod : ElementFilter.methodsIn(source.getEnclosedElements())) {
+ Overlay methodOverlay = overlay(sourceMethod);
+ ExecutableElement targetMethod = null;
+ if (methodOverlay != null || hasParameterOverlay(sourceMethod)) {
+ if (!sourceMethod.getModifiers().contains(Modifier.ABSTRACT)) {
+ throw invalid("@JsonMixin method selector must be abstract", sourceMethod);
+ }
+ targetMethod =
+ matchMethod(
+ elements,
+ types,
+ target,
+ source,
+ sourceMethod,
+ methodOverlay != null && methodOverlay.mentions(JSON_CREATOR));
+ }
+ if (methodOverlay != null) {
+ overlays.put(targetMethod, methodOverlay);
+ }
+ if (targetMethod != null) {
+ matchParameters(overlays, sourceMethod, targetMethod);
+ }
+ }
+ for (ExecutableElement sourceConstructor :
+ ElementFilter.constructorsIn(source.getEnclosedElements())) {
+ Overlay constructorOverlay = overlay(sourceConstructor);
+ ExecutableElement targetConstructor = null;
+ if (constructorOverlay != null || hasParameterOverlay(sourceConstructor)) {
+ targetConstructor = matchConstructor(types, target, source, sourceConstructor);
+ }
+ if (constructorOverlay != null) {
+ overlays.put(targetConstructor, constructorOverlay);
+ }
+ if (targetConstructor != null) {
+ matchParameters(overlays, sourceConstructor, targetConstructor);
+ }
+ }
+ return new JsonMixinAnnotations(
+ target, source, Collections.unmodifiableMap(new IdentityHashMap<>(overlays)));
+ }
+
+ TypeElement target() {
+ return target;
+ }
+
+ TypeElement source() {
+ return source;
+ }
+
+ boolean isEmpty() {
+ return overlays.isEmpty();
+ }
+
+ AnnotationMirror annotation(Element element, String annotationName) {
+ Overlay overlay = overlays.get(element);
+ if (overlay != null) {
+ AnnotationMirror replacement = overlay.replacements.get(annotationName);
+ if (replacement != null) {
+ return replacement;
+ }
+ if (overlay.removals.contains(annotationName)) {
+ return null;
+ }
+ }
+ if (element instanceof TypeElement
+ && !element.equals(target)
+ && (annotationName.equals(JSON_CODEC) || annotationName.equals(JSON_PROPERTY_ORDER))
+ && isRemoved(target, annotationName)) {
+ return null;
+ }
+ return declaredAnnotation(element, annotationName);
+ }
+
+ private boolean isRemoved(Element element, String annotationName) {
+ Overlay overlay = overlays.get(element);
+ return overlay != null && overlay.removals.contains(annotationName);
+ }
+
+ boolean hasJsonAnnotations(Element element) {
+ for (String annotationName : MAPPING_ANNOTATIONS) {
+ if (annotation(element, annotationName) != null) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ void collectAnnotations(Element element, Set<String> annotationTypes) {
+ for (String annotationName : MAPPING_ANNOTATIONS) {
+ if (annotation(element, annotationName) != null) {
+ annotationTypes.add(annotationName);
+ }
+ }
+ }
+
+ List<Element> sourceSelectors() {
+ List<Element> selectors = new ArrayList<>(overlays.size());
+ for (Overlay overlay : overlays.values()) {
+ selectors.add(overlay.source);
+ }
+ return selectors;
+ }
+
+ List<Element> targetSelectors() {
+ return new ArrayList<>(overlays.keySet());
+ }
+
+ private static void validateTypes(TypeElement target, TypeElement source) {
+ ElementKind sourceKind = source.getKind();
+ NestingKind nestingKind = source.getNestingKind();
+ if (!(sourceKind == ElementKind.INTERFACE
+ || sourceKind == ElementKind.CLASS && source.getModifiers().contains(Modifier.ABSTRACT))
+ || nestingKind == NestingKind.LOCAL
+ || nestingKind == NestingKind.ANONYMOUS
+ || nestingKind == NestingKind.MEMBER && !source.getModifiers().contains(Modifier.STATIC)) {
+ throw invalid("@JsonMixin source must be a named interface or static abstract class", source);
+ }
+ ElementKind targetKind = target.getKind();
+ if (!(targetKind == ElementKind.CLASS
+ || targetKind == ElementKind.INTERFACE
+ || targetKind == ElementKind.ENUM
+ || targetKind.name().equals("RECORD"))) {
+ throw invalid("@JsonMixin target must be a class, interface, enum, or Record", source);
+ }
+ if (target.equals(source)) {
+ throw invalid("@JsonMixin source and target must be different types", source);
+ }
+ if (!source.getInterfaces().isEmpty()) {
+ throw invalid("@JsonMixin source must not extend or implement another type", source);
+ }
+ TypeMirror superclass = source.getSuperclass();
+ if (sourceKind == ElementKind.CLASS
+ && superclass.getKind() != TypeKind.NONE
+ && !superclass.toString().equals("java.lang.Object")) {
+ throw invalid("@JsonMixin source must not extend or implement another type", source);
+ }
+ }
+
+ private static VariableElement matchField(
+ Elements elements,
+ Types types,
+ TypeElement target,
+ TypeElement source,
+ VariableElement selector) {
+ List<VariableElement> matches = new ArrayList<>();
+ TypeElement current = target;
+ while (current != null && !current.getQualifiedName().contentEquals("java.lang.Object")) {
+ for (VariableElement field : ElementFilter.fieldsIn(current.getEnclosedElements())) {
+ if (field.getKind() != ElementKind.ENUM_CONSTANT
+ && !field.getModifiers().contains(Modifier.STATIC)
+ && field.getSimpleName().contentEquals(selector.getSimpleName())
+ && sameErasure(types, field.asType(), selector.asType())) {
+ matches.add(field);
+ }
+ }
+ TypeMirror superclass = current.getSuperclass();
+ Element superElement =
+ superclass.getKind() == TypeKind.NONE ? null : types.asElement(superclass);
+ current = superElement instanceof TypeElement ? (TypeElement) superElement : null;
+ }
+ return oneMatch(elements, target, source, selector, "field", matches);
+ }
+
+ private static ExecutableElement matchMethod(
+ Elements elements,
+ Types types,
+ TypeElement target,
+ TypeElement source,
+ ExecutableElement selector,
+ boolean creatorSelector) {
+ List<ExecutableElement> matches = new ArrayList<>();
+ Set<ExecutableElement> seen = Collections.newSetFromMap(new IdentityHashMap<>());
+ if (creatorSelector) {
+ for (ExecutableElement method : ElementFilter.methodsIn(target.getEnclosedElements())) {
+ if (matchesMethod(types, selector, method) && seen.add(method)) {
+ matches.add(method);
+ }
+ }
+ } else {
+ for (ExecutableElement method : ElementFilter.methodsIn(elements.getAllMembers(target))) {
+ if (method.getModifiers().contains(Modifier.PUBLIC)
+ && matchesMethod(types, selector, method)
+ && seen.add(method)) {
+ matches.add(method);
+ }
+ }
+ for (TypeElement owner : classHierarchy(types, target)) {
+ for (ExecutableElement method : ElementFilter.methodsIn(owner.getEnclosedElements())) {
+ if (!method.getModifiers().contains(Modifier.PUBLIC)
+ && matchesMethod(types, selector, method)
+ && seen.add(method)) {
+ matches.add(method);
+ }
+ }
+ }
+ }
+ return oneMatch(elements, target, source, selector, "method", matches);
+ }
+
+ private static List<TypeElement> classHierarchy(Types types, TypeElement target) {
+ List<TypeElement> hierarchy = new ArrayList<>();
+ TypeElement current = target;
+ while (current != null && !current.getQualifiedName().contentEquals("java.lang.Object")) {
+ hierarchy.add(current);
+ TypeMirror superclass = current.getSuperclass();
+ Element superElement =
+ superclass.getKind() == TypeKind.NONE ? null : types.asElement(superclass);
+ current = superElement instanceof TypeElement ? (TypeElement) superElement : null;
+ }
+ return hierarchy;
+ }
+
+ private static boolean matchesMethod(
+ Types types, ExecutableElement selector, ExecutableElement candidate) {
+ if (!candidate.getSimpleName().contentEquals(selector.getSimpleName())
+ || !sameErasure(types, candidate.getReturnType(), selector.getReturnType())) {
+ return false;
+ }
+ List<? extends VariableElement> sourceParameters = selector.getParameters();
+ List<? extends VariableElement> targetParameters = candidate.getParameters();
+ if (sourceParameters.size() != targetParameters.size()) {
+ return false;
+ }
+ for (int i = 0; i < sourceParameters.size(); i++) {
+ if (!sameErasure(types, sourceParameters.get(i).asType(), targetParameters.get(i).asType())) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static ExecutableElement matchConstructor(
+ Types types, TypeElement target, TypeElement source, ExecutableElement selector) {
+ List<ExecutableElement> matches = new ArrayList<>();
+ for (ExecutableElement constructor :
+ ElementFilter.constructorsIn(target.getEnclosedElements())) {
+ if (sameParameters(types, selector, constructor)) {
+ matches.add(constructor);
+ }
+ }
+ return oneMatch(null, target, source, selector, "constructor", matches);
+ }
+
+ private static boolean sameParameters(
+ Types types, ExecutableElement left, ExecutableElement right) {
+ List<? extends VariableElement> leftParameters = left.getParameters();
+ List<? extends VariableElement> rightParameters = right.getParameters();
+ if (leftParameters.size() != rightParameters.size()) {
+ return false;
+ }
+ for (int i = 0; i < leftParameters.size(); i++) {
+ if (!sameErasure(types, leftParameters.get(i).asType(), rightParameters.get(i).asType())) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static boolean sameErasure(Types types, TypeMirror left, TypeMirror right) {
+ return types.isSameType(types.erasure(left), types.erasure(right));
+ }
+
+ private static void matchParameters(
+ Map<Element, Overlay> overlays,
+ ExecutableElement sourceExecutable,
+ ExecutableElement targetExecutable) {
+ List<? extends VariableElement> sourceParameters = sourceExecutable.getParameters();
+ List<? extends VariableElement> targetParameters = targetExecutable.getParameters();
+ for (int i = 0; i < sourceParameters.size(); i++) {
+ Overlay overlay = overlay(sourceParameters.get(i));
+ if (overlay != null) {
+ overlays.put(targetParameters.get(i), overlay);
+ }
+ }
+ }
+
+ private static boolean hasParameterOverlay(ExecutableElement executable) {
+ for (VariableElement parameter : executable.getParameters()) {
+ if (overlay(parameter) != null) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static <T extends Element> T oneMatch(
+ Elements elements,
+ TypeElement target,
+ TypeElement source,
+ Element selector,
+ String kind,
+ List<T> matches) {
+ if (matches.size() == 1) {
+ return matches.get(0);
+ }
+ String targetName =
+ elements == null
+ ? target.getQualifiedName().toString()
+ : elements.getBinaryName(target).toString();
+ throw invalid(
+ "@JsonMixin "
+ + kind
+ + " selector "
+ + selector
+ + " on "
+ + source.getQualifiedName()
+ + (matches.isEmpty() ? " does not match " : " ambiguously matches ")
+ + targetName,
+ selector);
+ }
+
+ private static Overlay overlay(Element sourceElement) {
+ if (declaredAnnotation(sourceElement, JSON_TYPE) != null) {
+ throw invalid("@JsonType cannot be declared by a JSON Mixin", sourceElement);
+ }
+ Map<String, AnnotationMirror> replacements = new LinkedHashMap<>();
+ for (AnnotationMirror mirror : sourceElement.getAnnotationMirrors()) {
+ String name = annotationName(mirror);
+ if (MAPPING_ANNOTATIONS.contains(name)) {
+ replacements.put(name, mirror);
+ }
+ }
+ Set<String> removals = new LinkedHashSet<>();
+ AnnotationMirror remove = declaredAnnotation(sourceElement, JSON_MIXIN_REMOVE);
+ if (remove != null) {
+ AnnotationValue value = annotationValue(remove, "value");
+ if (value == null || !(value.getValue() instanceof List<?>)) {
+ throw invalid("@JsonMixinRemove must declare at least one annotation", sourceElement);
+ }
+ for (Object rawEntry : (List<?>) value.getValue()) {
+ Object entry =
+ rawEntry instanceof AnnotationValue ? ((AnnotationValue) rawEntry).getValue() : null;
+ if (!(entry instanceof TypeMirror)) {
+ throw invalid("Invalid @JsonMixinRemove annotation type", sourceElement);
+ }
+ Element annotationElement =
+ ((TypeMirror) entry).getKind() == TypeKind.DECLARED
+ ? ((javax.lang.model.type.DeclaredType) entry).asElement()
+ : null;
+ if (!(annotationElement instanceof TypeElement)) {
+ throw invalid("Invalid @JsonMixinRemove annotation type", sourceElement);
+ }
+ String name = ((TypeElement) annotationElement).getQualifiedName().toString();
+ if (!MAPPING_ANNOTATIONS.contains(name)) {
+ throw invalid("Unsupported @JsonMixinRemove annotation " + name, sourceElement);
+ }
+ if (!removals.add(name)) {
+ throw invalid("Duplicate @JsonMixinRemove annotation " + name, sourceElement);
+ }
+ if (replacements.containsKey(name)) {
+ throw invalid(
+ "Cannot declare and remove " + name + " on the same selector", sourceElement);
+ }
+ validateRemovalKind(sourceElement, (TypeElement) annotationElement);
+ }
+ if (removals.isEmpty()) {
+ throw invalid("@JsonMixinRemove must declare at least one annotation", sourceElement);
+ }
+ }
+ return replacements.isEmpty() && removals.isEmpty()
+ ? null
+ : new Overlay(
+ sourceElement,
+ Collections.unmodifiableMap(replacements),
+ Collections.unmodifiableSet(removals));
+ }
+
+ private static void validateRemovalKind(Element element, TypeElement annotationType) {
+ ElementType elementType = elementType(element.getKind());
+ Target target = annotationType.getAnnotation(Target.class);
+ if (elementType != null
+ && (target == null || Arrays.asList(target.value()).contains(elementType))) {
+ return;
+ }
+ throw invalid(
+ "Cannot remove " + annotationType.getQualifiedName() + " from " + element.getKind(),
+ element);
+ }
+
+ private static ElementType elementType(ElementKind kind) {
+ if (kind == ElementKind.CLASS
+ || kind == ElementKind.INTERFACE
+ || kind == ElementKind.ENUM
+ || kind.name().equals("RECORD")) {
+ return ElementType.TYPE;
+ }
+ if (kind == ElementKind.FIELD) {
+ return ElementType.FIELD;
+ }
+ if (kind == ElementKind.METHOD) {
+ return ElementType.METHOD;
+ }
+ if (kind == ElementKind.CONSTRUCTOR) {
+ return ElementType.CONSTRUCTOR;
+ }
+ if (kind == ElementKind.PARAMETER) {
+ return ElementType.PARAMETER;
+ }
+ return null;
+ }
+
+ private static AnnotationMirror declaredAnnotation(Element element, String annotationName) {
+ for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
+ if (annotationName(mirror).equals(annotationName)) {
+ return mirror;
+ }
+ }
+ return null;
+ }
+
+ private static String annotationName(AnnotationMirror mirror) {
+ Element annotationElement = mirror.getAnnotationType().asElement();
+ return annotationElement instanceof TypeElement
+ ? ((TypeElement) annotationElement).getQualifiedName().toString()
+ : mirror.getAnnotationType().toString();
+ }
+
+ private static AnnotationValue annotationValue(AnnotationMirror annotation, String name) {
+ Element annotationElement = annotation.getAnnotationType().asElement();
+ if (!(annotationElement instanceof TypeElement)) {
+ return null;
+ }
+ for (Element enclosed : annotationElement.getEnclosedElements()) {
+ if (enclosed instanceof ExecutableElement && enclosed.getSimpleName().contentEquals(name)) {
+ ExecutableElement member = (ExecutableElement) enclosed;
+ for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
+ annotation.getElementValues().entrySet()) {
+ if (entry.getKey().equals(member)) {
+ return entry.getValue();
+ }
+ }
+ return member.getDefaultValue();
+ }
+ }
+ return null;
+ }
+
+ private static InvalidJsonMixinException invalid(String message, Element element) {
+ return new InvalidJsonMixinException(message, element);
+ }
+
+ static final class InvalidJsonMixinException extends RuntimeException {
+ final Element element;
+
+ InvalidJsonMixinException(String message, Element element) {
+ super(message);
+ this.element = element;
+ }
+ }
+
+ private static final class Overlay {
+ final Element source;
+ final Map<String, AnnotationMirror> replacements;
+ final Set<String> removals;
+
+ Overlay(Element source, Map<String, AnnotationMirror> replacements, Set<String> removals) {
+ this.source = source;
+ this.replacements = replacements;
+ this.removals = removals;
+ }
+
+ boolean mentions(String annotationName) {
+ return replacements.containsKey(annotationName) || removals.contains(annotationName);
+ }
+ }
+}
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 0c45462c7..ec2d0d715 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
@@ -57,10 +57,12 @@ import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
import javax.tools.StandardLocation;
-/** Generates precise Android R8 rules for {@code JsonType} models. */
+/** Generates JSON companions and platform configuration for annotated models and Mixins. */
final class JsonTypeProcessor {
private static final String JSON_PACKAGE = "org.apache.fory.json";
private static final String JSON_TYPE = JSON_PACKAGE + ".annotation.JsonType";
+ private static final String JSON_MIXIN = JSON_PACKAGE + ".annotation.JsonMixin";
+ 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_CREATOR = JSON_PACKAGE + ".annotation.JsonCreator";
@@ -68,12 +70,14 @@ final class JsonTypeProcessor {
private static final String JSON_VALUE = JSON_PACKAGE + ".annotation.JsonValue";
private static final String JSON_RAW_VALUE = JSON_PACKAGE + ".annotation.JsonRawValue";
private static final String JSON_BASE64 = JSON_PACKAGE + ".annotation.JsonBase64";
+ private static final String JSON_UNWRAPPED = JSON_PACKAGE + ".annotation.JsonUnwrapped";
private static final String BASE64_CODEC = JSON_PACKAGE + ".codec.Base64ByteArrayCodec";
private static final String JSON_ANY_GETTER = JSON_PACKAGE + ".annotation.JsonAnyGetter";
private static final String JSON_ANY_SETTER = JSON_PACKAGE + ".annotation.JsonAnySetter";
private static final String NO_JSON_VALUE_CODEC = JSON_CODEC + "$NoJsonValueCodec";
private static final String NO_MAP_KEY_CODEC = JSON_CODEC + "$NoMapKeyCodec";
private static final String R8_PREFIX = "META-INF/proguard/fory-json-";
+ private static final String R8_MIXIN_PREFIX = "META-INF/proguard/fory-json-mixin-";
private static final String NATIVE_IMAGE_PREFIX =
"META-INF/native-image/org.apache.fory/fory-json-";
private static final String[] CODEC_MEMBERS = {
@@ -86,6 +90,8 @@ final class JsonTypeProcessor {
private final Types types;
private final GeneratedJsonCodecSourceWriter codecSourceWriter;
private final Set<String> processedTypes = new HashSet<>();
+ private final Set<String> processedMixins = new HashSet<>();
+ private final Map<String, TypeElement> pendingMixins = new LinkedHashMap<>();
JsonTypeProcessor(ProcessingEnvironment environment) {
filer = environment.getFiler();
@@ -96,8 +102,10 @@ final class JsonTypeProcessor {
}
void process(RoundEnvironment roundEnvironment) {
+ validateMixinControls(roundEnvironment);
TypeElement jsonType = elements.getTypeElement(JSON_TYPE);
if (jsonType == null) {
+ processMixins(roundEnvironment);
return;
}
Deque<TypeElement> pending = new ArrayDeque<>();
@@ -112,6 +120,9 @@ final class JsonTypeProcessor {
if (!processedTypes.add(binaryName)) {
continue;
}
+ if (hasAnnotation(type, JSON_MIXIN)) {
+ continue;
+ }
try {
Model model = inspect(type);
if (hasAnnotation(type, JSON_TYPE)) {
@@ -143,33 +154,272 @@ final class JsonTypeProcessor {
type);
}
}
+ processMixins(roundEnvironment);
+ }
+
+ private void validateMixinControls(RoundEnvironment roundEnvironment) {
+ TypeElement removeType = elements.getTypeElement(JSON_MIXIN_REMOVE);
+ if (removeType == null) {
+ return;
+ }
+ for (Element element : roundEnvironment.getElementsAnnotatedWith(removeType)) {
+ TypeElement owner = enclosingType(element);
+ if (owner == null || !hasAnnotation(owner, JSON_MIXIN)) {
+ messager.printMessage(
+ Diagnostic.Kind.ERROR,
+ "@JsonMixinRemove is valid only inside a direct @JsonMixin source",
+ element);
+ }
+ }
+ }
+
+ private static TypeElement enclosingType(Element element) {
+ Element current = element;
+ while (current != null && !(current instanceof TypeElement)) {
+ current = current.getEnclosingElement();
+ }
+ return current instanceof TypeElement ? (TypeElement) current : null;
+ }
+
+ private void processMixins(RoundEnvironment roundEnvironment) {
+ TypeElement jsonMixin = elements.getTypeElement(JSON_MIXIN);
+ if (jsonMixin == null) {
+ return;
+ }
+ for (Element element : roundEnvironment.getElementsAnnotatedWith(jsonMixin)) {
+ if (element instanceof TypeElement) {
+ TypeElement mixin = (TypeElement) element;
+ pendingMixins.put(elements.getBinaryName(mixin).toString(), mixin);
+ }
+ }
+ List<Map.Entry<String, TypeElement>> candidates = new ArrayList<>(pendingMixins.entrySet());
+ for (Map.Entry<String, TypeElement> candidate : candidates) {
+ String mixinBinaryName = candidate.getKey();
+ TypeElement mixin = candidate.getValue();
+ TypeElement currentMixin = elements.getTypeElement(mixin.getQualifiedName());
+ if (currentMixin != null) {
+ mixin = currentMixin;
+ pendingMixins.put(mixinBinaryName, mixin);
+ }
+ if (processedMixins.contains(mixinBinaryName)) {
+ pendingMixins.remove(mixinBinaryName);
+ continue;
+ }
+ try {
+ TypeElement target = mixinTarget(mixin);
+ if (target == null) {
+ if (roundEnvironment.processingOver()) {
+ messager.printMessage(
+ Diagnostic.Kind.ERROR,
+ "Cannot resolve @JsonMixin target for " + mixinBinaryName,
+ mixin);
+ pendingMixins.remove(mixinBinaryName);
+ }
+ continue;
+ }
+ processedMixins.add(mixinBinaryName);
+ pendingMixins.remove(mixinBinaryName);
+ JsonMixinAnnotations annotations =
+ JsonMixinAnnotations.resolve(elements, types, target, mixin);
+ if (annotations.isEmpty()) {
+ continue;
+ }
+ boolean directTypeCodec = codecSourceWriter.hasDirectTypeCodec(target, annotations);
+ boolean typeCodec =
+ directTypeCodec || codecSourceWriter.hasCompleteTypeCodec(target, annotations);
+ GeneratedJsonCodecSourceWriter.Result generated =
+ typeCodec ? null : codecSourceWriter.writePair(annotations);
+ Model model =
+ typeCodec
+ ? inspectTypeCodec(target, annotations, directTypeCodec)
+ : inspectModel(target, annotations);
+ model.mixin = mixin;
+ model.resourceIdentity = mixinBinaryName;
+ collectMixinSource(annotations, model);
+ collectMixinTargets(annotations, model);
+ if (generated != null) {
+ model.nameTypes.add(model.binaryName);
+ model.nameTypes.add(mixinBinaryName);
+ model.companionBinaryName = generated.companionBinaryName;
+ model.companionHasAnySetter = generated.hasAnySetter;
+ model.companionHasCreator = generated.hasCreator;
+ model.companionHasCreatorFactory = generated.hasCreatorFactory;
+ model.companionIsRecord = generated.record;
+ for (GeneratedJsonCodecSourceWriter.MemberRule member : generated.r8Members) {
+ model.addR8Member(new R8Member(member.ownerBinaryName, member.declaration));
+ }
+ }
+ if (!typeCodec) {
+ collectPairClosure(model, target, annotations);
+ }
+ model.sort();
+ emitR8(model);
+ emitNativeImageProperties(model);
+ } catch (JsonMixinAnnotations.InvalidJsonMixinException e) {
+ messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage(), e.element);
+ } catch (GeneratedJsonCodecSourceWriter.InvalidJsonTypeException e) {
+ messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage(), e.element);
+ } catch (InvalidJsonTypeException e) {
+ messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage(), e.element);
+ } catch (RuntimeException e) {
+ messager.printMessage(
+ Diagnostic.Kind.ERROR,
+ "Failed to process Fory JSON Mixin " + mixinBinaryName + ": " + e.getMessage(),
+ mixin);
+ }
+ }
+ }
+
+ private TypeElement mixinTarget(TypeElement mixin) {
+ AnnotationMirror annotation = annotationMirror(mixin, JSON_MIXIN);
+ if (annotation == null) {
+ throw new InvalidJsonTypeException("Missing @JsonMixin declaration", mixin);
+ }
+ AnnotationValue value = annotationValue(annotation, "target");
+ if (value == null || !(value.getValue() instanceof TypeMirror)) {
+ throw new InvalidJsonTypeException("@JsonMixin must declare a target type", mixin);
+ }
+ TypeMirror target = (TypeMirror) value.getValue();
+ if (target.getKind() == TypeKind.ERROR) {
+ return null;
+ }
+ TypeElement targetElement = asTypeElement(target);
+ if (targetElement == null) {
+ throw new InvalidJsonTypeException("@JsonMixin target must be a declared type", mixin);
+ }
+ return targetElement;
+ }
+
+ private void collectMixinSource(JsonMixinAnnotations annotations, Model model) {
+ TypeElement source = annotations.source();
+ String sourceBinaryName = elements.getBinaryName(source).toString();
+ collectAnnotations(source, model.annotationTypes);
+ model.annotationOwnerTypes.add(sourceBinaryName);
+ Set<Element> retained = Collections.newSetFromMap(new java.util.IdentityHashMap<>());
+ List<Element> selectors = annotations.sourceSelectors();
+ for (Element selector : selectors) {
+ collectAnnotations(selector, model.annotationTypes);
+ Element retainedElement =
+ selector.getKind() == ElementKind.PARAMETER ? selector.getEnclosingElement() : selector;
+ if (retainedElement instanceof ExecutableElement) {
+ ExecutableElement executable = (ExecutableElement) retainedElement;
+ collectAnnotations(executable.getParameters(), model.annotationTypes);
+ }
+ if (!retained.add(retainedElement)) {
+ continue;
+ }
+ if (retainedElement.getKind() == ElementKind.FIELD) {
+ VariableElement field = (VariableElement) retainedElement;
+ model.addR8Member(R8Member.field(field, typeName(field.asType())));
+ } else if (retainedElement.getKind() == ElementKind.METHOD) {
+ ExecutableElement method = (ExecutableElement) retainedElement;
+ model.addR8Member(
+ R8Member.method(method, typeName(method.getReturnType()), typeNames(method)));
+ } else if (retainedElement.getKind() == ElementKind.CONSTRUCTOR) {
+ ExecutableElement constructor = (ExecutableElement) retainedElement;
+ model.addR8Member(R8Member.constructor(constructor, typeNames(constructor)));
+ }
+ }
}
private Model inspect(TypeElement target) {
+ return inspectModel(target, null);
+ }
+
+ private Model inspectTypeCodec(
+ TypeElement target, JsonMixinAnnotations annotations, boolean directTypeCodec) {
String binaryName = elements.getBinaryName(target).toString();
Model model = new Model(target, binaryName);
+ model.annotations = annotations;
+ model.annotationOwnerTypes.add(binaryName);
+ collectTypeCodec(target, model);
+ if (directTypeCodec) {
+ collectValueValidation(target, annotations, model);
+ }
+ return model;
+ }
+
+ private void collectValueValidation(
+ TypeElement target, JsonMixinAnnotations annotations, Model model) {
+ boolean hasValue = false;
+ for (TypeElement owner : classHierarchy(target)) {
+ for (VariableElement field : ElementFilter.fieldsIn(owner.getEnclosedElements())) {
+ if (hasAnnotation(annotations, field, JSON_VALUE)) {
+ hasValue = true;
+ collectAnnotations(annotations, field, model.annotationTypes);
+ collectOccurrenceCodec(annotations, field, model);
+ model.addR8Member(R8Member.field(field, typeName(field.asType())));
+ }
+ }
+ }
+ for (ExecutableElement method : jsonMethods(target, annotations)) {
+ if (hasAnnotation(annotations, method, JSON_VALUE)) {
+ hasValue = true;
+ collectAnnotations(annotations, method, model.annotationTypes);
+ collectOccurrenceCodec(annotations, method, model);
+ model.addR8Member(
+ R8Member.method(method, typeName(method.getReturnType()), typeNames(method)));
+ }
+ }
+ for (TypeElement owner : classHierarchy(target)) {
+ for (ExecutableElement method : ElementFilter.methodsIn(owner.getEnclosedElements())) {
+ if (!method.getModifiers().contains(Modifier.PUBLIC)
+ && hasAnnotation(annotations, method, JSON_VALUE)) {
+ hasValue = true;
+ collectAnnotations(annotations, method, model.annotationTypes);
+ collectOccurrenceCodec(annotations, method, model);
+ model.addR8Member(
+ R8Member.method(method, typeName(method.getReturnType()), typeNames(method)));
+ }
+ }
+ }
+ if (!hasValue) {
+ return;
+ }
+ for (ExecutableElement constructor :
+ ElementFilter.constructorsIn(target.getEnclosedElements())) {
+ if (hasAnnotation(annotations, constructor, JSON_CREATOR)) {
+ collectAnnotations(annotations, constructor, model.annotationTypes);
+ collectAnnotations(annotations, constructor.getParameters(), model.annotationTypes);
+ model.addR8Member(R8Member.constructor(constructor, typeNames(constructor)));
+ }
+ }
+ for (ExecutableElement method : ElementFilter.methodsIn(target.getEnclosedElements())) {
+ if (hasAnnotation(annotations, method, JSON_CREATOR)) {
+ collectAnnotations(annotations, method, model.annotationTypes);
+ collectAnnotations(annotations, method.getParameters(), model.annotationTypes);
+ model.addR8Member(
+ R8Member.method(method, typeName(method.getReturnType()), typeNames(method)));
+ }
+ }
+ }
+
+ private Model inspectModel(TypeElement target, JsonMixinAnnotations annotations) {
+ String binaryName = elements.getBinaryName(target).toString();
+ Model model = new Model(target, binaryName);
+ model.annotations = annotations;
DeclaredType targetType = (DeclaredType) target.asType();
- collectAnnotations(target, model.annotationTypes);
- collectCodecAnnotation(annotationMirror(target, JSON_CODEC), model);
+ collectAnnotations(annotations, target, model.annotationTypes);
+ collectCodecAnnotation(annotationMirror(annotations, target, JSON_CODEC), model);
model.annotationOwnerTypes.add(binaryName);
List<TypeElement> classes = classHierarchy(target);
Collections.reverse(classes);
for (TypeElement type : classes) {
- collectAnnotations(type, model.annotationTypes);
- collectCodecAnnotation(annotationMirror(type, JSON_CODEC), model);
- if (hasJsonAnnotations(type)) {
+ collectAnnotations(annotations, type, model.annotationTypes);
+ collectCodecAnnotation(annotationMirror(annotations, type, JSON_CODEC), model);
+ if (hasJsonAnnotations(annotations, type)) {
model.annotationOwnerTypes.add(elements.getBinaryName(type).toString());
}
for (VariableElement field : ElementFilter.fieldsIn(type.getEnclosedElements())) {
- collectAnnotations(field, model.annotationTypes);
- collectOccurrenceCodec(field, model);
+ collectAnnotations(annotations, field, model.annotationTypes);
+ collectOccurrenceCodec(annotations, field, model);
if (field.getKind() == ElementKind.ENUM_CONSTANT) {
model.addR8Member(R8Member.field(field, typeName(field.asType())));
continue;
}
// Runtime validation still needs to see annotated members that are not JSON properties.
- if (isEligibleField(field) || hasJsonAnnotations(field)) {
+ if (isEligibleField(field) || hasJsonAnnotations(annotations, field)) {
model.addR8Member(R8Member.field(field, typeName(field.asType())));
collectTypeEndpoints(types.asMemberOf(targetType, field), model);
}
@@ -177,39 +427,39 @@ final class JsonTypeProcessor {
}
for (TypeElement owner : allDeclarations(target)) {
- collectAnnotations(owner, model.annotationTypes);
- collectCodecAnnotation(annotationMirror(owner, JSON_CODEC), model);
- if (hasJsonAnnotations(owner)) {
+ collectAnnotations(annotations, owner, model.annotationTypes);
+ collectCodecAnnotation(annotationMirror(annotations, owner, JSON_CODEC), model);
+ if (hasJsonAnnotations(annotations, owner)) {
model.annotationOwnerTypes.add(elements.getBinaryName(owner).toString());
}
}
// Ordinary property rules follow Java's effective method set. An unannotated override
// suppresses the inherited declaration, while creators remain exact to the target declaration.
- List<ExecutableElement> jsonMethods = jsonMethods(target);
+ List<ExecutableElement> jsonMethods = jsonMethods(target, annotations);
for (ExecutableElement method : jsonMethods) {
TypeElement owner = (TypeElement) method.getEnclosingElement();
ExecutableType resolvedMethod = (ExecutableType) types.asMemberOf(targetType, method);
model.addR8Member(
R8Member.method(method, typeName(method.getReturnType()), typeNames(method)));
- collectAnnotations(method, model.annotationTypes);
- collectOccurrenceCodec(method, model);
- collectAnnotations(method.getParameters(), model.annotationTypes);
- collectCodecAnnotations(method.getParameters(), model);
+ collectAnnotations(annotations, method, model.annotationTypes);
+ collectOccurrenceCodec(annotations, method, model);
+ collectAnnotations(annotations, method.getParameters(), model.annotationTypes);
+ collectCodecAnnotations(annotations, method.getParameters(), model);
collectTypeEndpoints(resolvedMethod.getReturnType(), model);
for (TypeMirror parameterType : resolvedMethod.getParameterTypes()) {
collectTypeEndpoints(parameterType, model);
}
- collectAnnotations(owner, model.annotationTypes);
+ collectAnnotations(annotations, owner, model.annotationTypes);
}
- collectValidationMethods(target, jsonMethods, model);
+ collectValidationMethods(target, jsonMethods, annotations, model);
for (ExecutableElement constructor :
ElementFilter.constructorsIn(target.getEnclosedElements())) {
- collectAnnotations(constructor, model.annotationTypes);
- collectAnnotations(constructor.getParameters(), model.annotationTypes);
- collectCodecAnnotations(constructor.getParameters(), model);
- boolean creator = hasAnnotation(constructor, JSON_CREATOR);
- if (creator || isNoArg(constructor) || hasJsonDeclaration(constructor)) {
+ collectAnnotations(annotations, constructor, model.annotationTypes);
+ collectAnnotations(annotations, constructor.getParameters(), model.annotationTypes);
+ collectCodecAnnotations(annotations, constructor.getParameters(), model);
+ boolean creator = hasAnnotation(annotations, constructor, JSON_CREATOR);
+ if (creator || isNoArg(constructor) || hasJsonDeclaration(annotations, constructor)) {
model.addR8Member(R8Member.constructor(constructor, typeNames(constructor)));
for (VariableElement parameter : constructor.getParameters()) {
collectTypeEndpoints(parameter.asType(), model);
@@ -219,15 +469,39 @@ final class JsonTypeProcessor {
return model;
}
- private void collectCodecAnnotations(List<? extends Element> sourceElements, Model model) {
+ private void collectCodecAnnotations(
+ JsonMixinAnnotations annotations, List<? extends Element> sourceElements, Model model) {
for (Element element : sourceElements) {
- collectCodecAnnotation(annotationMirror(element, JSON_CODEC), model);
+ collectCodecAnnotation(annotationMirror(annotations, element, JSON_CODEC), model);
+ }
+ }
+
+ private void collectMixinTargets(JsonMixinAnnotations annotations, Model model) {
+ Set<Element> retained = Collections.newSetFromMap(new java.util.IdentityHashMap<>());
+ for (Element selector : annotations.targetSelectors()) {
+ Element declaration =
+ selector.getKind() == ElementKind.PARAMETER ? selector.getEnclosingElement() : selector;
+ if (!retained.add(declaration)) {
+ continue;
+ }
+ if (declaration.getKind() == ElementKind.FIELD) {
+ VariableElement field = (VariableElement) declaration;
+ model.addR8Member(R8Member.field(field, typeName(field.asType())));
+ } else if (declaration.getKind() == ElementKind.METHOD) {
+ ExecutableElement method = (ExecutableElement) declaration;
+ model.addR8Member(
+ R8Member.method(method, typeName(method.getReturnType()), typeNames(method)));
+ } else if (declaration.getKind() == ElementKind.CONSTRUCTOR) {
+ ExecutableElement constructor = (ExecutableElement) declaration;
+ model.addR8Member(R8Member.constructor(constructor, typeNames(constructor)));
+ }
}
}
- private void collectOccurrenceCodec(Element element, Model model) {
- collectCodecAnnotation(annotationMirror(element, JSON_CODEC), model);
- if (hasAnnotation(element, JSON_BASE64)) {
+ private void collectOccurrenceCodec(
+ JsonMixinAnnotations annotations, Element element, Model model) {
+ collectCodecAnnotation(annotationMirror(annotations, element, JSON_CODEC), model);
+ if (hasAnnotation(annotations, element, JSON_BASE64)) {
model.codecTypes.add(BASE64_CODEC);
}
}
@@ -254,10 +528,12 @@ final class JsonTypeProcessor {
}
private void emitR8(Model model) {
- String resourceName = R8_PREFIX + model.binaryName + ".pro";
+ String resourceName =
+ (model.mixin == null ? R8_PREFIX : R8_MIXIN_PREFIX) + model.resourceIdentity + ".pro";
try {
javax.tools.FileObject file =
- filer.createResource(StandardLocation.CLASS_OUTPUT, "", resourceName, model.target);
+ filer.createResource(
+ StandardLocation.CLASS_OUTPUT, "", resourceName, model.originatingElements());
try (Writer writer = file.openWriter()) {
writer.write(writeR8(model));
}
@@ -277,7 +553,8 @@ final class JsonTypeProcessor {
NATIVE_IMAGE_PREFIX + model.companionBinaryName + "/native-image.properties";
try {
javax.tools.FileObject file =
- filer.createResource(StandardLocation.CLASS_OUTPUT, "", resourceName, model.target);
+ filer.createResource(
+ StandardLocation.CLASS_OUTPUT, "", resourceName, model.originatingElements());
try (Writer writer = file.openWriter()) {
writer.write("Args=--initialize-at-build-time=" + model.companionBinaryName + "$Factory\n");
}
@@ -310,6 +587,7 @@ final class JsonTypeProcessor {
for (Map.Entry<String, List<R8Member>> entry : membersByOwner.entrySet()) {
boolean preserveName =
model.binaryFallbackTypes.contains(entry.getKey())
+ || model.nameTypes.contains(entry.getKey())
|| model.companionBinaryName != null && model.binaryName.equals(entry.getKey());
builder
.append("-keep,allowoptimization")
@@ -391,7 +669,12 @@ final class JsonTypeProcessor {
private List<TypeElement> classLiteralSubtypes(
TypeElement target, Set<String> binaryFallbackTypes) {
- AnnotationMirror subtypes = annotationMirror(target, JSON_SUB_TYPES);
+ return classLiteralSubtypes(target, binaryFallbackTypes, null);
+ }
+
+ private List<TypeElement> classLiteralSubtypes(
+ TypeElement target, Set<String> binaryFallbackTypes, JsonMixinAnnotations annotations) {
+ AnnotationMirror subtypes = annotationMirror(annotations, target, JSON_SUB_TYPES);
if (subtypes == null) {
return Collections.emptyList();
}
@@ -427,6 +710,74 @@ final class JsonTypeProcessor {
return subtypesToProcess;
}
+ private void collectPairClosure(
+ Model model, TypeElement target, JsonMixinAnnotations annotations) {
+ Set<String> visited = new HashSet<>();
+ visited.add(elements.getBinaryName(target).toString());
+ Deque<TypeElement> pending = new ArrayDeque<>();
+ pending.addAll(classLiteralSubtypes(target, model.binaryFallbackTypes, annotations));
+ pending.addAll(unwrappedChildren(target, annotations));
+ while (!pending.isEmpty()) {
+ TypeElement type = pending.removeFirst();
+ String binaryName = elements.getBinaryName(type).toString();
+ if (!visited.add(binaryName)) {
+ continue;
+ }
+ Model child = inspectModel(type, null);
+ model.merge(child);
+ pending.addAll(classLiteralSubtypes(type, model.binaryFallbackTypes, null));
+ pending.addAll(unwrappedChildren(type, null));
+ }
+ }
+
+ private List<TypeElement> unwrappedChildren(
+ TypeElement target, JsonMixinAnnotations annotations) {
+ LinkedHashMap<String, TypeElement> children = new LinkedHashMap<>();
+ DeclaredType targetType = (DeclaredType) target.asType();
+ for (TypeElement owner : classHierarchy(target)) {
+ for (VariableElement field : ElementFilter.fieldsIn(owner.getEnclosedElements())) {
+ if (annotationMirror(annotations, field, JSON_UNWRAPPED) != null) {
+ addChild(types.asMemberOf(targetType, field), children);
+ }
+ }
+ }
+ for (ExecutableElement method : jsonMethods(target, annotations)) {
+ ExecutableType resolved = (ExecutableType) types.asMemberOf(targetType, method);
+ if (annotationMirror(annotations, method, JSON_UNWRAPPED) != null) {
+ if (resolved.getParameterTypes().isEmpty()
+ && resolved.getReturnType().getKind() != TypeKind.VOID) {
+ addChild(resolved.getReturnType(), children);
+ } else if (resolved.getParameterTypes().size() == 1) {
+ addChild(resolved.getParameterTypes().get(0), children);
+ }
+ }
+ List<? extends VariableElement> parameters = method.getParameters();
+ for (int i = 0; i < parameters.size(); i++) {
+ if (annotationMirror(annotations, parameters.get(i), JSON_UNWRAPPED) != null) {
+ addChild(resolved.getParameterTypes().get(i), children);
+ }
+ }
+ }
+ for (ExecutableElement constructor :
+ ElementFilter.constructorsIn(target.getEnclosedElements())) {
+ List<? extends VariableElement> parameters = constructor.getParameters();
+ for (VariableElement parameter : parameters) {
+ if (annotationMirror(annotations, parameter, JSON_UNWRAPPED) != null) {
+ addChild(parameter.asType(), children);
+ }
+ }
+ }
+ return new ArrayList<>(children.values());
+ }
+
+ private void addChild(TypeMirror type, Map<String, TypeElement> children) {
+ TypeElement child = asTypeElement(types.erasure(type));
+ if (child == null || child.getQualifiedName().contentEquals("java.lang.Object")) {
+ return;
+ }
+ children.put(elements.getBinaryName(child).toString(), child);
+ }
+
private List<TypeElement> classHierarchy(TypeElement target) {
List<TypeElement> hierarchy = new ArrayList<>();
TypeElement current = target;
@@ -438,11 +789,12 @@ final class JsonTypeProcessor {
return hierarchy;
}
- private List<ExecutableElement> jsonMethods(TypeElement target) {
+ private List<ExecutableElement> jsonMethods(
+ TypeElement target, JsonMixinAnnotations annotations) {
Map<String, ExecutableElement> methods = new LinkedHashMap<>();
for (ExecutableElement method : ElementFilter.methodsIn(elements.getAllMembers(target))) {
TypeElement owner = (TypeElement) method.getEnclosingElement();
- if (!isJsonMethod(method, owner.equals(target))) {
+ if (!isJsonMethod(annotations, method, owner.equals(target))) {
continue;
}
String key = elements.getBinaryName(owner) + "#" + methodSignature(method);
@@ -454,7 +806,10 @@ final class JsonTypeProcessor {
}
private void collectValidationMethods(
- TypeElement target, List<ExecutableElement> effectiveMethods, Model model) {
+ TypeElement target,
+ List<ExecutableElement> effectiveMethods,
+ JsonMixinAnnotations annotations,
+ Model model) {
// Runtime validation scans declared class methods, including private and static declarations
// that property discovery cannot select. R8 must retain those declarations and annotations so
// release builds reject the same invalid model instead of silently losing the annotation.
@@ -465,14 +820,14 @@ final class JsonTypeProcessor {
for (TypeElement owner : classHierarchy(target)) {
boolean targetDeclaration = owner.equals(target);
for (ExecutableElement method : ElementFilter.methodsIn(owner.getEnclosedElements())) {
- if (!hasMethodValidationAnnotation(method)
+ if (!hasMethodValidationAnnotation(annotations, method)
|| !isEffectiveValidationMethod(method, targetDeclaration, effectiveKeys)) {
continue;
}
- collectAnnotations(method, model.annotationTypes);
- collectAnnotations(method.getParameters(), model.annotationTypes);
- collectOccurrenceCodec(method, model);
- collectCodecAnnotations(method.getParameters(), model);
+ collectAnnotations(annotations, method, model.annotationTypes);
+ collectAnnotations(annotations, method.getParameters(), model.annotationTypes);
+ collectOccurrenceCodec(annotations, method, model);
+ collectCodecAnnotations(annotations, method.getParameters(), model);
collectTypeEndpoints(method.getReturnType(), model);
for (VariableElement parameter : method.getParameters()) {
collectTypeEndpoints(parameter.asType(), model);
@@ -492,8 +847,9 @@ final class JsonTypeProcessor {
|| effectiveKeys.contains(methodKey(method));
}
- private boolean hasMethodValidationAnnotation(ExecutableElement method) {
- return hasJsonDeclaration(method);
+ private boolean hasMethodValidationAnnotation(
+ JsonMixinAnnotations annotations, ExecutableElement method) {
+ return hasJsonDeclaration(annotations, method);
}
private String methodKey(ExecutableElement method) {
@@ -527,18 +883,19 @@ final class JsonTypeProcessor {
return new ArrayList<>(owners.values());
}
- private boolean isJsonMethod(ExecutableElement method, boolean targetDeclaration) {
- if (hasAnnotation(method, JSON_PROPERTY)
- || hasAnnotation(method, JSON_ANY_GETTER)
- || hasAnnotation(method, JSON_ANY_SETTER)
- || hasAnnotation(method, JSON_CODEC)
- || hasAnnotation(method, JSON_VALUE)
- || hasAnnotation(method, JSON_RAW_VALUE)
- || hasAnnotation(method, JSON_BASE64)
- || hasJsonAnnotations(method.getParameters())) {
+ private boolean isJsonMethod(
+ JsonMixinAnnotations annotations, ExecutableElement method, boolean targetDeclaration) {
+ if (hasAnnotation(annotations, method, JSON_PROPERTY)
+ || hasAnnotation(annotations, method, JSON_ANY_GETTER)
+ || hasAnnotation(annotations, method, JSON_ANY_SETTER)
+ || hasAnnotation(annotations, method, JSON_CODEC)
+ || hasAnnotation(annotations, method, JSON_VALUE)
+ || hasAnnotation(annotations, method, JSON_RAW_VALUE)
+ || hasAnnotation(annotations, method, JSON_BASE64)
+ || hasJsonAnnotations(annotations, method.getParameters())) {
return true;
}
- if (targetDeclaration && hasAnnotation(method, JSON_CREATOR)) {
+ if (targetDeclaration && hasAnnotation(annotations, method, JSON_CREATOR)) {
return true;
}
Set<Modifier> modifiers = method.getModifiers();
@@ -604,34 +961,21 @@ final class JsonTypeProcessor {
if (type.getKind() == ElementKind.ANNOTATION_TYPE) {
return;
}
- // Match JsonSharedRegistry's declaration lookup: a direct declaration hides all inherited
- // declarations; otherwise only the most-specific inherited declarations are inspected.
- // Their owners must remain reflection-visible as well as their selected codec constructors.
- AnnotationMirror direct = annotationMirror(type, JSON_CODEC);
+ JsonMixinAnnotations annotations = type.equals(model.target) ? model.annotations : null;
+ // Match JsonSharedRegistry's declaration lookup: a direct declaration hides inherited
+ // declarations; otherwise runtime reads every inherited declaration before selecting the
+ // most-specific frontier. This does not select a built-in mapping.
+ AnnotationMirror direct = annotationMirror(annotations, type, JSON_CODEC);
if (direct != null) {
collectCodecDeclaration(type, direct, model);
return;
}
- List<TypeElement> candidates = new ArrayList<>();
List<TypeElement> declarations = allDeclarations(type);
for (int i = 1; i < declarations.size(); i++) {
TypeElement declaration = declarations.get(i);
- if (annotationMirror(declaration, JSON_CODEC) != null) {
- candidates.add(declaration);
- }
- }
- for (TypeElement candidate : candidates) {
- boolean dominated = false;
- for (TypeElement other : candidates) {
- if (!candidate.equals(other)
- && types.isAssignable(
- types.erasure(other.asType()), types.erasure(candidate.asType()))) {
- dominated = true;
- break;
- }
- }
- if (!dominated) {
- collectCodecDeclaration(candidate, annotationMirror(candidate, JSON_CODEC), model);
+ AnnotationMirror annotation = annotationMirror(annotations, declaration, JSON_CODEC);
+ if (annotation != null) {
+ collectCodecDeclaration(declaration, annotation, model);
}
}
}
@@ -692,6 +1036,18 @@ final class JsonTypeProcessor {
}
}
+ private void collectAnnotations(
+ JsonMixinAnnotations annotations, Element element, Set<String> annotationTypes) {
+ if (annotations == null) {
+ collectAnnotations(element, annotationTypes);
+ return;
+ }
+ annotations.collectAnnotations(element, annotationTypes);
+ if (annotationMirror(element, JSON_TYPE) != null) {
+ annotationTypes.add(JSON_TYPE);
+ }
+ }
+
private void collectAnnotations(
List<? extends Element> sourceElements, Set<String> annotationTypes) {
for (Element element : sourceElements) {
@@ -699,6 +1055,15 @@ final class JsonTypeProcessor {
}
}
+ private void collectAnnotations(
+ JsonMixinAnnotations annotations,
+ List<? extends Element> sourceElements,
+ Set<String> annotationTypes) {
+ for (Element element : sourceElements) {
+ collectAnnotations(annotations, element, annotationTypes);
+ }
+ }
+
private AnnotationMirror annotationMirror(Element element, String annotationName) {
for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
Element annotationType = mirror.getAnnotationType().asElement();
@@ -710,10 +1075,22 @@ final class JsonTypeProcessor {
return null;
}
+ private AnnotationMirror annotationMirror(
+ JsonMixinAnnotations annotations, Element element, String annotationName) {
+ return annotations == null
+ ? annotationMirror(element, annotationName)
+ : annotations.annotation(element, annotationName);
+ }
+
private boolean hasAnnotation(Element element, String annotationName) {
return annotationMirror(element, annotationName) != null;
}
+ private boolean hasAnnotation(
+ JsonMixinAnnotations annotations, Element element, String annotationName) {
+ return annotationMirror(annotations, element, annotationName) != null;
+ }
+
private boolean hasJsonAnnotations(Element element) {
for (AnnotationMirror annotation : element.getAnnotationMirrors()) {
Element annotationType = annotation.getAnnotationType().asElement();
@@ -728,17 +1105,26 @@ final class JsonTypeProcessor {
return false;
}
- private boolean hasJsonAnnotations(List<? extends Element> sourceElements) {
+ private boolean hasJsonAnnotations(JsonMixinAnnotations annotations, Element element) {
+ return annotations == null
+ ? hasJsonAnnotations(element)
+ : annotations.hasJsonAnnotations(element);
+ }
+
+ private boolean hasJsonAnnotations(
+ JsonMixinAnnotations annotations, List<? extends Element> sourceElements) {
for (Element element : sourceElements) {
- if (hasJsonAnnotations(element)) {
+ if (hasJsonAnnotations(annotations, element)) {
return true;
}
}
return false;
}
- private boolean hasJsonDeclaration(ExecutableElement executable) {
- return hasJsonAnnotations(executable) || hasJsonAnnotations(executable.getParameters());
+ private boolean hasJsonDeclaration(
+ JsonMixinAnnotations annotations, ExecutableElement executable) {
+ return hasJsonAnnotations(annotations, executable)
+ || hasJsonAnnotations(annotations, executable.getParameters());
}
private AnnotationValue annotationValue(AnnotationMirror annotation, String name) {
@@ -771,6 +1157,10 @@ final class JsonTypeProcessor {
final Set<String> codecTypes = new LinkedHashSet<>();
final Set<String> binaryFallbackTypes = new LinkedHashSet<>();
final Set<String> annotationOwnerTypes = new LinkedHashSet<>();
+ final Set<String> nameTypes = new LinkedHashSet<>();
+ JsonMixinAnnotations annotations;
+ TypeElement mixin;
+ String resourceIdentity;
String companionBinaryName;
boolean companionHasAnySetter;
boolean companionHasCreator;
@@ -780,6 +1170,7 @@ final class JsonTypeProcessor {
Model(TypeElement target, String binaryName) {
this.target = target;
this.binaryName = binaryName;
+ resourceIdentity = binaryName;
}
void addR8Member(R8Member member) {
@@ -790,6 +1181,7 @@ final class JsonTypeProcessor {
boolean hasNestedIdentity() {
return binaryName.indexOf('$') >= 0
+ || containsNested(nameTypes)
|| containsNested(binaryFallbackTypes)
|| containsNested(annotationOwnerTypes)
|| containsNested(containerTypes)
@@ -804,6 +1196,23 @@ final class JsonTypeProcessor {
sortSet(codecTypes);
sortSet(binaryFallbackTypes);
sortSet(annotationOwnerTypes);
+ sortSet(nameTypes);
+ }
+
+ void merge(Model other) {
+ for (R8Member member : other.r8Members) {
+ addR8Member(member);
+ }
+ annotationTypes.addAll(other.annotationTypes);
+ containerTypes.addAll(other.containerTypes);
+ codecTypes.addAll(other.codecTypes);
+ binaryFallbackTypes.addAll(other.binaryFallbackTypes);
+ annotationOwnerTypes.addAll(other.annotationOwnerTypes);
+ nameTypes.addAll(other.nameTypes);
+ }
+
+ Element[] originatingElements() {
+ return mixin == null ? new Element[] {target} : new Element[] {mixin, target};
}
private static boolean containsNested(Set<String> names) {
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 4ccc8d55e..e1940089b 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
@@ -56,6 +56,7 @@ import org.testng.annotations.Test;
public class JsonTypeProcessorTest {
private static final String RULE_PREFIX = "META-INF/proguard/fory-json-";
+ private static final String MIXIN_RULE_PREFIX = "META-INF/proguard/fory-json-mixin-";
private static final String NATIVE_IMAGE_PREFIX =
"META-INF/native-image/org.apache.fory/fory-json-";
@@ -67,6 +68,415 @@ public class JsonTypeProcessorTest {
assertFalse(result.hasGeneratedResource(RULE_PREFIX + "test.Plain.pro"));
}
+ @Test
+ public void emptyMixin() throws Exception {
+ CompilationResult result =
+ compile(
+ "test.Target",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.JsonMixin;\n"
+ + "public class Target { public int id; }\n"
+ + "@JsonMixin(target = Target.class) interface EmptyMixin {}\n");
+ assertTrue(result.success, result.diagnostics());
+ String companion = "test.EmptyMixin_ForyJsonMixin_test_x2e_Target_ForyJsonCodec";
+ assertFalse(result.hasGeneratedSource(companion.replace('.', '/') + ".java"));
+ assertFalse(result.hasGeneratedResource(MIXIN_RULE_PREFIX + "test.EmptyMixin.pro"));
+ assertFalse(
+ result.hasGeneratedResource(NATIVE_IMAGE_PREFIX + companion + "/native-image.properties"));
+ }
+
+ @Test
+ public void mixinPairArtifacts() throws Exception {
+ CompilationResult result =
+ compile(
+ "test.Person",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "public final class Person {\n"
+ + " public Address address;\n"
+ + " public String body;\n"
+ + " private Person(String body) { this.body = body; }\n"
+ + " public static Person create(String body) { return new Person(body); }\n"
+ + "}\n"
+ + "class Address { public String city; }\n"
+ + "@JsonMixin(target = Person.class) abstract class PersonMixin {\n"
+ + " @JsonUnwrapped(prefix = \"address_\") Address address;\n"
+ + " @JsonRawValue String body;\n"
+ + " @JsonCreator({\"body\"}) abstract Person create(String body);\n"
+ + "}\n");
+ assertTrue(result.success, result.diagnostics());
+ String base = "PersonMixin_ForyJsonMixin_test_x2e_Person";
+ assertTrue(result.hasGeneratedSource("test/" + base + "_ForyJsonCodec.java"));
+ String rules = result.generatedResource(MIXIN_RULE_PREFIX + "test.PersonMixin.pro");
+ assertTrue(rules.contains("-keep,allowoptimization class test.Person"), rules);
+ assertTrue(rules.contains("-keep,allowoptimization class test.PersonMixin"), rules);
+ assertTrue(rules.contains("test.Address address;"), rules);
+ assertTrue(rules.contains("test.Person create(java.lang.String);"), rules);
+ assertTrue(rules.contains("java.lang.String city;"), rules);
+ assertTrue(rules.contains("class test." + base + "_ForyJsonCodec {"), rules);
+ }
+
+ @Test
+ public void mixinTypeCodecRules() throws Exception {
+ CompilationResult result =
+ compile(
+ "test.CodecTarget",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "@JsonCodec(CodecMixin.InheritedCodec.class) interface InheritedContract {}\n"
+ + "public final class CodecTarget implements InheritedContract {\n"
+ + " public int selected;\n"
+ + " @JsonValue public String value;\n"
+ + " public String unrelated;\n"
+ + " public Child child;\n"
+ + " @JsonCreator public CodecTarget(String value) { this.value = value; }\n"
+ + " public static final class Child { public String nested; }\n"
+ + "}\n"
+ + "@JsonMixin(target = CodecTarget.class)\n"
+ + "@JsonCodec(CodecMixin.Codec.class) abstract class CodecMixin {\n"
+ + " @JsonProperty int selected;\n"
+ + valueCodec("Codec")
+ + valueCodec("InheritedCodec")
+ + "}\n");
+ assertTrue(result.success, result.diagnostics());
+ String base = "CodecMixin_ForyJsonMixin_test_x2e_CodecTarget";
+ assertFalse(result.hasGeneratedSource("test/" + base + "_ForyJsonCodec.java"));
+ String rules = result.generatedResource(MIXIN_RULE_PREFIX + "test.CodecMixin.pro");
+ assertTrue(
+ rules.contains(
+ "-keepclassmembers,allowoptimization class test.CodecTarget {\n"
+ + " <init>(java.lang.String);\n"
+ + " int selected;\n"
+ + " java.lang.String value;\n"
+ + "}"),
+ rules);
+ assertTrue(rules.contains("class test.CodecMixin$Codec { public <init>(); }"), rules);
+ assertFalse(rules.contains("class test.CodecMixin$InheritedCodec { public <init>(); }"), rules);
+ assertFalse(rules.contains("class test.InheritedContract"), rules);
+ assertFalse(rules.contains("java.lang.String unrelated;"), rules);
+ assertFalse(rules.contains("test.CodecTarget$Child child;"), rules);
+ assertFalse(rules.contains("java.lang.String nested;"), rules);
+ }
+
+ @Test
+ public void mixinInheritedCodecRules() throws Exception {
+ CompilationResult result =
+ compile(
+ "test.InheritedTarget",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "@JsonCodec(value = Codecs.RootCodec.class, "
+ + "elementCodec = Codecs.RootCodec.class) interface Root {}\n"
+ + "@JsonCodec(Codecs.ChildCodec.class) interface Child extends Root {}\n"
+ + "public final class InheritedTarget implements Child {\n"
+ + " public int id;\n"
+ + " public String unrelated;\n"
+ + " @JsonUnwrapped public Details details;\n"
+ + " public static final class Details { public String nested; }\n"
+ + "}\n"
+ + "@JsonMixin(target = InheritedTarget.class) abstract class InheritedMixin {\n"
+ + " @JsonProperty int id;\n"
+ + "}\n"
+ + "final class Codecs {\n"
+ + valueCodec("RootCodec")
+ + valueCodec("ChildCodec")
+ + "}\n");
+ assertTrue(result.success, result.diagnostics());
+ String rules = result.generatedResource(MIXIN_RULE_PREFIX + "test.InheritedMixin.pro");
+ assertTrue(rules.contains("class test.Codecs$RootCodec { public <init>(); }"), rules);
+ assertTrue(rules.contains("class test.Codecs$ChildCodec { public <init>(); }"), rules);
+ assertTrue(rules.contains("class test.Root"), rules);
+ assertTrue(rules.contains("class test.Child"), rules);
+ assertFalse(rules.contains("java.lang.String unrelated;"), rules);
+ assertFalse(rules.contains("test.InheritedTarget$Details details;"), rules);
+ assertFalse(rules.contains("java.lang.String nested;"), rules);
+ }
+
+ @Test
+ public void mixinRuntimePipeline() throws Exception {
+ CompilationResult result =
+ compile(
+ "test.MixinTarget",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "public final class MixinTarget {\n"
+ + " private final int id;\n"
+ + " private final String name;\n"
+ + " private MixinTarget(int id, String name) { this.id = id; this.name = name; }\n"
+ + " public int getId() { return id; }\n"
+ + " public String getName() { return name; }\n"
+ + " public static MixinTarget create(int id, String name) {\n"
+ + " return new MixinTarget(id, name);\n"
+ + " }\n"
+ + "}\n"
+ + "@JsonMixin(target = MixinTarget.class)\n"
+ + "@JsonPropertyOrder({\"id\", \"name\"})\n"
+ + "interface MixinTargetAnnotations {\n"
+ + " @JsonProperty(\"user_id\") int getId();\n"
+ + " @JsonCreator({\"id\", \"name\"}) MixinTarget create(int id, String name);\n"
+ + "}\n");
+ assertTrue(result.success, result.diagnostics());
+ ClassLoader loader = result.classLoader();
+ Class<?> target = loader.loadClass("test.MixinTarget");
+ Class<?> mixin = loader.loadClass("test.MixinTargetAnnotations");
+ String base = "test.MixinTargetAnnotations_ForyJsonMixin_test_x2e_MixinTarget";
+ GeneratedJsonCodec<?> codec = generatedCodec(loader, base + "_ForyJsonCodec");
+ assertEquals(codec.type(), target);
+ Object value = target.getMethod("create", int.class, String.class).invoke(null, 7, "pair");
+ for (boolean codegen : new boolean[] {false, true}) {
+ ForyJson json =
+ ForyJson.builder()
+ .withCodegen(codegen)
+ .withAsyncCompilation(false)
+ .withClassLoader(loader)
+ .registerMixin(mixin)
+ .build();
+ String text = json.toJson(value);
+ assertEquals(text, "{\"user_id\":7,\"name\":\"pair\"}");
+ Object decoded = json.fromJson(text, target);
+ assertEquals(target.getMethod("getId").invoke(decoded), 7);
+ assertEquals(target.getMethod("getName").invoke(decoded), "pair");
+ }
+ }
+
+ @Test
+ public void mixinRecordPipeline() throws Exception {
+ assumeJava16Source();
+ CompilationResult result =
+ compile(
+ "test.MixinRecord",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "public record MixinRecord(int id, String name) {}\n"
+ + "@JsonMixin(target = MixinRecord.class)\n"
+ + "@JsonPropertyOrder({\"id\", \"name\"})\n"
+ + "abstract class MixinRecordAnnotations {\n"
+ + " @JsonProperty(\"user_id\") int id;\n"
+ + " @JsonProperty(\"display_name\") String name;\n"
+ + " @JsonProperty(\"user_id\") abstract int id();\n"
+ + " @JsonProperty(\"display_name\") abstract String name();\n"
+ + " MixinRecordAnnotations(@JsonProperty(\"user_id\") int id,\n"
+ + " @JsonProperty(\"display_name\") String name) {}\n"
+ + "}\n");
+ assertTrue(result.success, result.diagnostics());
+ String base = "MixinRecordAnnotations_ForyJsonMixin_test_x2e_MixinRecord";
+ assertTrue(result.hasGeneratedSource("test/" + base + "_ForyJsonCodec.java"));
+ ClassLoader loader = result.classLoader();
+ Class<?> target = loader.loadClass("test.MixinRecord");
+ Class<?> mixin = loader.loadClass("test.MixinRecordAnnotations");
+ Object value = target.getConstructor(int.class, String.class).newInstance(9, "record");
+ for (boolean codegen : new boolean[] {false, true}) {
+ ForyJson json =
+ ForyJson.builder()
+ .withCodegen(codegen)
+ .withAsyncCompilation(false)
+ .withClassLoader(loader)
+ .registerMixin(mixin)
+ .build();
+ String text = json.toJson(value);
+ assertEquals(text, "{\"user_id\":9,\"display_name\":\"record\"}");
+ Object decoded = json.fromJson(text, target);
+ assertEquals(target.getMethod("id").invoke(decoded), 9);
+ assertEquals(target.getMethod("name").invoke(decoded), "record");
+ }
+ }
+
+ @Test
+ public void mixinValueRecordPipeline() throws Exception {
+ assumeJava16Source();
+ CompilationResult result =
+ compile(
+ "test.MixinValueRecord",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "public record MixinValueRecord(String value) {}\n"
+ + "@JsonMixin(target = MixinValueRecord.class)\n"
+ + "abstract class MixinValueRecordAnnotations {\n"
+ + " @JsonValue String value;\n"
+ + " @JsonValue abstract String value();\n"
+ + " @JsonCreator MixinValueRecordAnnotations(String value) {}\n"
+ + "}\n");
+ assertTrue(result.success, result.diagnostics());
+ String base = "MixinValueRecordAnnotations_ForyJsonMixin_test_x2e_MixinValueRecord";
+ assertTrue(result.hasGeneratedSource("test/" + base + "_ForyJsonCodec.java"));
+ ClassLoader loader = result.classLoader();
+ Class<?> target = loader.loadClass("test.MixinValueRecord");
+ Class<?> mixin = loader.loadClass("test.MixinValueRecordAnnotations");
+ Object value = target.getConstructor(String.class).newInstance("write");
+ for (boolean codegen : new boolean[] {false, true}) {
+ ForyJson json =
+ ForyJson.builder()
+ .withCodegen(codegen)
+ .withAsyncCompilation(false)
+ .withClassLoader(loader)
+ .registerMixin(mixin)
+ .build();
+ assertEquals(json.toJson(value), "\"write\"");
+ Object decoded = json.fromJson("\"read\"", target);
+ assertEquals(target.getMethod("value").invoke(decoded), "read");
+ }
+ }
+
+ @Test
+ public void mixinNamesDoNotCollide() throws Exception {
+ Map<String, String> sources = new LinkedHashMap<>();
+ sources.put("test.Target", "package test; public class Target { public int id; }\n");
+ sources.put(
+ "test.FirstMixin",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "@JsonMixin(target = Target.class) public abstract class FirstMixin {\n"
+ + " @JsonProperty(\"first\") int id;\n"
+ + "}\n");
+ sources.put(
+ "test.SecondMixin",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "@JsonMixin(target = Target.class) public abstract class SecondMixin {\n"
+ + " @JsonProperty(\"second\") int id;\n"
+ + "}\n");
+ CompilationResult result = compile(sources);
+ assertTrue(result.success, result.diagnostics());
+ assertTrue(
+ result.hasGeneratedSource(
+ "test/FirstMixin_ForyJsonMixin_test_x2e_Target_ForyJsonCodec.java"));
+ assertTrue(
+ result.hasGeneratedSource(
+ "test/SecondMixin_ForyJsonMixin_test_x2e_Target_ForyJsonCodec.java"));
+ assertTrue(result.hasGeneratedResource(MIXIN_RULE_PREFIX + "test.FirstMixin.pro"));
+ assertTrue(result.hasGeneratedResource(MIXIN_RULE_PREFIX + "test.SecondMixin.pro"));
+ }
+
+ @Test
+ public void mixinSelectorShape() throws Exception {
+ CompilationResult staticField =
+ compile(
+ "test.StaticFieldMixin",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "class Target { public int id; }\n"
+ + "@JsonMixin(target = Target.class) abstract class StaticFieldMixin {\n"
+ + " @JsonProperty static int id;\n"
+ + "}\n");
+ assertFalse(staticField.success);
+ assertTrue(
+ staticField.diagnostics().contains("field selector must be an instance field"),
+ staticField.diagnostics());
+
+ CompilationResult concreteMethod =
+ compile(
+ "test.ConcreteMethodMixin",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "class Target { public String getName() { return null; } }\n"
+ + "@JsonMixin(target = Target.class) abstract class ConcreteMethodMixin {\n"
+ + " @JsonProperty String getName() { return null; }\n"
+ + "}\n");
+ assertFalse(concreteMethod.success);
+ assertTrue(
+ concreteMethod.diagnostics().contains("method selector must be abstract"),
+ concreteMethod.diagnostics());
+
+ CompilationResult jsonTypeSource =
+ compile(
+ "test.JsonTypeMixin",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "class Target { public int id; }\n"
+ + "@JsonType @JsonMixin(target = Target.class) interface JsonTypeMixin {}\n");
+ assertFalse(jsonTypeSource.success);
+ assertTrue(
+ jsonTypeSource.diagnostics().contains("@JsonType cannot be declared by a JSON Mixin"),
+ jsonTypeSource.diagnostics());
+ assertFalse(jsonTypeSource.hasGeneratedResource(RULE_PREFIX + "test.JsonTypeMixin.pro"));
+ }
+
+ @Test
+ public void mixinInaccessibleAnySetter() throws Exception {
+ CompilationResult result =
+ compile(
+ "test.Owner",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "public final class Owner {\n"
+ + " private static final class HiddenValue { public int id; }\n"
+ + " public static final class Target {\n"
+ + " private HiddenValue extra;\n"
+ + " public void putExtra(String name, HiddenValue value) { extra = value; }\n"
+ + " public int getExtraId() { return extra.id; }\n"
+ + " }\n"
+ + " @JsonMixin(target = Target.class) public interface Mixin {\n"
+ + " @JsonAnySetter void putExtra(String name, HiddenValue value);\n"
+ + " }\n"
+ + "}\n");
+ assertTrue(result.success, result.diagnostics());
+ ClassLoader loader = result.classLoader();
+ Class<?> target = loader.loadClass("test.Owner$Target");
+ Class<?> mixin = loader.loadClass("test.Owner$Mixin");
+ ForyJson json = ForyJson.builder().withClassLoader(loader).registerMixin(mixin).build();
+ Object value = json.fromJson("{\"answer\":{\"id\":42}}", target);
+ assertEquals(target.getMethod("getExtraId").invoke(value), 42);
+ }
+
+ @Test
+ public void directMixinRemoveRejected() throws Exception {
+ CompilationResult result =
+ compile(
+ "test.InvalidRemove",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "@JsonMixinRemove(JsonPropertyOrder.class) class InvalidRemove {}\n");
+ assertFalse(result.success);
+ assertTrue(
+ result.diagnostics().contains("valid only inside a direct @JsonMixin source"),
+ result.diagnostics());
+ }
+
+ @Test
+ public void inheritedCodecRemovalRules() throws Exception {
+ CompilationResult result =
+ compile(
+ "test.CodecBarrierMixin",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "@JsonCodec(Codec.class) class Base {}\n"
+ + "@JsonCodec(EndpointCodec.class) class Endpoint {}\n"
+ + "class Target extends Base { public Endpoint endpoint; }\n"
+ + "@JsonMixin(target = Target.class)\n"
+ + "@JsonMixinRemove(JsonCodec.class) interface CodecBarrierMixin {}\n"
+ + "class Codec implements org.apache.fory.json.codec.JsonValueCodec<Object> {\n"
+ + " public Codec() {}\n"
+ + " public void writeString(org.apache.fory.json.writer.StringJsonWriter w, Object v) {}\n"
+ + " public void writeUtf8(org.apache.fory.json.writer.Utf8JsonWriter w, Object v) {}\n"
+ + " public Object readLatin1(org.apache.fory.json.reader.Latin1JsonReader r) { return null; }\n"
+ + " public Object readUtf16(org.apache.fory.json.reader.Utf16JsonReader r) { return null; }\n"
+ + " public Object readUtf8(org.apache.fory.json.reader.Utf8JsonReader r) { return null; }\n"
+ + "}\n"
+ + "final class EndpointCodec extends Codec { public EndpointCodec() {}\n"
+ + "}\n");
+ assertTrue(result.success, result.diagnostics());
+ String rules = result.generatedResource(MIXIN_RULE_PREFIX + "test.CodecBarrierMixin.pro");
+ assertFalse(rules.contains("class test.Codec "), rules);
+ assertFalse(rules.contains("class test.Base"), rules);
+ assertTrue(rules.contains("class test.EndpointCodec { public <init>(); }"), rules);
+ }
+
+ @Test
+ public void mixinCreatorIsExact() throws Exception {
+ CompilationResult result =
+ compile(
+ "test.CreatorMixin",
+ "package test;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "class Base { public static Target create(String name) { return null; } }\n"
+ + "class Target extends Base {}\n"
+ + "@JsonMixin(target = Target.class) interface CreatorMixin {\n"
+ + " @JsonCreator({\"name\"}) Target create(String name);\n"
+ + "}\n");
+ assertFalse(result.success);
+ assertTrue(result.diagnostics().contains("does not match test.Target"), result.diagnostics());
+ }
+
@Test
public void jsonTypeRules() throws Exception {
CompilationResult result =
@@ -876,7 +1286,7 @@ public class JsonTypeProcessorTest {
"package test;\n"
+ "import java.util.List;\n"
+ "import org.apache.fory.json.annotation.*;\n"
- + "@JsonCodec(DeclarationModel.ShadowedCodec.class) interface BaseContract {}\n"
+ + "@JsonCodec(DeclarationModel.DominatedCodec.class) interface BaseContract {}\n"
+ "@JsonCodec(DeclarationModel.InheritedCodec.class)\n"
+ "interface ValueContract extends BaseContract {}\n"
+ "@JsonCodec(DeclarationModel.DirectCodec.class)\n"
@@ -889,7 +1299,7 @@ public class JsonTypeProcessorTest {
+ " public List<DirectValue> nested;\n"
+ " @JsonCreator public DeclarationModel(\n"
+ " @JsonProperty(\"parameter\") ParameterValue parameter) {}\n"
- + valueCodecs("DirectCodec", "InheritedCodec", "ParameterCodec", "ShadowedCodec")
+ + valueCodecs("DirectCodec", "InheritedCodec", "ParameterCodec", "DominatedCodec")
+ "}\n");
assertTrue(result.success, result.diagnostics());
String rules = result.generatedResource(RULE_PREFIX + "test.DeclarationModel.pro");
@@ -902,9 +1312,9 @@ public class JsonTypeProcessorTest {
assertTrue(rules.contains("class test.DirectValue"), rules);
assertTrue(rules.contains("class test.ValueContract"), rules);
assertTrue(rules.contains("class test.ParameterValue"), rules);
- assertFalse(
- rules.contains("class test.DeclarationModel$ShadowedCodec { public <init>(); }"), rules);
- assertFalse(rules.contains("class test.BaseContract"), rules);
+ assertTrue(
+ rules.contains("class test.DeclarationModel$DominatedCodec { public <init>(); }"), rules);
+ assertTrue(rules.contains("class test.BaseContract"), rules);
}
@Test
diff --git a/java/fory-json/README.md b/java/fory-json/README.md
index ed7503975..e13e9d33f 100644
--- a/java/fory-json/README.md
+++ b/java/fory-json/README.md
@@ -349,6 +349,7 @@ original key type. Null map keys are rejected.
| `withConcurrencyLevel(int)` | `max(1, 2 * processors)` | Number of reusable concurrent operation states |
| `withBufferSizeLimitBytes(int)` | 2 MiB | Maximum reusable capacity retained by each pooled writer |
| `registerCodec(type, codec)` | None | Replace the exact class's complete JSON codec |
+| `registerMixin(mixinType)` | None | Apply one annotation Mixin to its exact declared target |
| `withTypeChecker(checker)` | No custom checker | Apply an application type policy in addition to Fory's disallow list |
Depth, concurrency level, and buffer retention limit must be positive. The cached-field-name limit
@@ -364,20 +365,83 @@ automatically disabled. Every other builder option keeps the behavior described
## JSON annotations
-Fory JSON defines fourteen annotations in `org.apache.fory.json.annotation`, including `JsonCodec` for
-complete-value codec selection and `JsonType` for generated model execution and retention.
-They are Fory JSON APIs, not Jackson, Gson, or Fory binary-protocol compatibility annotations.
+Fory JSON provides these mapping annotations in `org.apache.fory.json.annotation`:
+`JsonAnyGetter`, `JsonAnyProperty`, `JsonAnySetter`, `JsonBase64`, `JsonCodec`, `JsonCreator`,
+`JsonIgnore`, `JsonProperty`, `JsonPropertyOrder`, `JsonRawValue`, `JsonSubTypes`, `JsonUnwrapped`,
+and `JsonValue`. `JsonType` is a separate build-time generation marker. They are Fory JSON APIs,
+not Jackson, Gson, or Fory binary-protocol compatibility annotations.
`JsonType` asks the annotation processor to generate direct property and creator operations plus
exact retention rules. It is not inherited, so annotate each eligible concrete model that needs a
generated companion. A directly annotated `JsonValue` Record also receives a companion for its
value accessor and canonical constructor. Ordinary unannotated classes may still use reflection; on
-Android they need application-authored exact R8 rules. Android-desugared Records require `JsonType`
-and the processor. A directly annotated model that uses the default object codec fails during codec
+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. A directly annotated model that uses the default object codec fails during codec
creation if its generated companion is missing.
See the [GraalVM guide](../../docs/guide/java/graalvm-support.md) and
[Android guide](../../docs/guide/java/android-support.md) for the platform workflows.
+### Mixins
+
+Use a JSON Mixin to apply Fory JSON mapping annotations to a class without modifying that class:
+
+```java
+import org.apache.fory.json.ForyJson;
+import org.apache.fory.json.annotation.JsonMixin;
+import org.apache.fory.json.annotation.JsonProperty;
+import org.apache.fory.json.annotation.JsonUnwrapped;
+
+@JsonMixin(target = ThirdPartyUser.class)
+abstract class ThirdPartyUserMixin {
+ @JsonProperty("user_id")
+ long id;
+
+ @JsonUnwrapped(prefix = "address_")
+ Address address;
+}
+
+ForyJson json = ForyJson.builder().registerMixin(ThirdPartyUserMixin.class).build();
+```
+
+A Mixin source is a named abstract class or interface, must not be local or anonymous, must not
+extend or implement another type, and is never instantiated. Its annotated fields, methods,
+constructors, and parameters select existing declarations on the exact target. The target continues
+to own all Java types, values, access, and construction. A registration for a base class does not
+affect a subclass, and an interface registration does not affect an implementation.
+
+The source may apply any mapping annotation listed above. Declaring an annotation
+on a matched source declaration replaces the target annotation of the same type as a whole; it does
+not merge individual annotation members. `JsonType` cannot be added or removed by a Mixin.
+
+Use `JsonMixinRemove` when the target's annotation should not be effective in this configuration:
+
+```java
+import org.apache.fory.json.annotation.JsonMixin;
+import org.apache.fory.json.annotation.JsonMixinRemove;
+import org.apache.fory.json.annotation.JsonRawValue;
+
+@JsonMixin(target = ThirdPartyMessage.class)
+abstract class QuotedMessageMixin {
+ @JsonMixinRemove(JsonRawValue.class)
+ String body;
+}
+```
+
+The source selector must match exactly one target declaration even when it only removes an
+annotation. Registering a different Mixin for the same target on one builder replaces the earlier
+registration. Re-registering the same source is harmless. Each `build()` snapshots the current
+last-registration-wins mapping, so later builder changes do not mutate an existing `ForyJson`. An
+empty source is a no-op and clears an earlier source for the same target when registered later.
+
+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 and GraalVM Native Image, compile non-empty Mixins with the Fory annotation processor
+so required generated operations and platform configuration are available. See the platform guides
+linked above.
+
### `JsonProperty`
`JsonProperty` configures the canonical name, serialization index, and null inclusion of one
@@ -1155,13 +1219,13 @@ The first `JsonAnySetter` parameter is the String property name. Its second para
Fory resolves each current value in this order:
-| Priority | Source |
-| -------: | ----------------------------------------- |
-| 1 | Current property or parameter `JsonCodec` |
-| 2 | Exact `registerCodec` registration |
-| 3 | Direct type `JsonCodec` declaration |
-| 4 | Inherited type declaration |
-| 5 | Built-in or default JSON mapping |
+| Priority | Source |
+| -------: | ------------------------------------------------- |
+| 1 | Current property or parameter `JsonCodec` |
+| 2 | Exact `registerCodec` registration |
+| 3 | Exact-target type `JsonCodec` after Mixin overlay |
+| 4 | Inherited-frontier type `JsonCodec` declaration |
+| 5 | Built-in or default JSON mapping |
One logical property may expose the annotation from its field, getter, setter parameter, creator
parameter, or record propagation. Repeated configurations must be identical; Fory does not merge
@@ -1188,9 +1252,10 @@ type-declaration codec is used for a more specific target, every decoded value m
assignable to that target.
The annotation has the same FIELD, METHOD, and PARAMETER behavior on the JVM, Android, and GraalVM
-Native Image. Ordinary Android classes may omit `JsonType` and provide equivalent exact rules;
-Android-desugared Records, including `JsonValue` Records, require `JsonType` and the processor.
-GraalVM object models follow the `JsonType` workflow in the
+Native Image. Ordinary Android classes may omit `JsonType` and provide equivalent exact rules.
+Android-desugared Records, including `JsonValue` Records, require processor-generated operations
+from either a direct `JsonType` declaration or a compiled exact `JsonMixin` pair. GraalVM object
+models follow the build-time workflow in the
[GraalVM guide](../../docs/guide/java/graalvm-support.md).
## Type validation and untrusted input
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 554c23f0b..ee4cfeec4 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
@@ -19,7 +19,10 @@
package org.apache.fory.json;
+import java.util.IdentityHashMap;
+import java.util.Map;
import java.util.Objects;
+import org.apache.fory.json.annotation.JsonMixin;
import org.apache.fory.json.codec.JsonValueCodec;
import org.apache.fory.json.resolver.CodecRegistry;
import org.apache.fory.platform.AndroidSupport;
@@ -55,6 +58,7 @@ public final class ForyJsonBuilder {
private int bufferSizeLimitBytes = 2 * 1024 * 1024;
private JsonTypeChecker typeChecker;
private final CodecRegistry codecRegistry = new CodecRegistry();
+ private final Map<Class<?>, Class<?>> mixins = new IdentityHashMap<>();
ForyJsonBuilder() {}
@@ -184,6 +188,42 @@ public final class ForyJsonBuilder {
return this;
}
+ /**
+ * Registers the JSON Mixin declared by {@code mixinType} for its exact target class.
+ *
+ * <p>Registering another Mixin for the same target replaces the previous registration. Existing
+ * {@link ForyJson} instances retain their immutable configuration snapshot. Only the final source
+ * for each target is structurally resolved when {@link #build()} creates the runtime; a
+ * superseded source is not resolved.
+ *
+ * @throws NullPointerException if {@code mixinType} is null
+ * @throws IllegalArgumentException if {@code mixinType} has no readable {@link JsonMixin}
+ * declaration
+ */
+ public ForyJsonBuilder registerMixin(Class<?> mixinType) {
+ Objects.requireNonNull(mixinType, "mixinType");
+ JsonMixin declaration;
+ try {
+ declaration = mixinType.getDeclaredAnnotation(JsonMixin.class);
+ } catch (RuntimeException | LinkageError e) {
+ throw new IllegalArgumentException(
+ "Cannot read JSON Mixin declaration " + mixinType.getName(), e);
+ }
+ if (declaration == null) {
+ throw new IllegalArgumentException(
+ "JSON Mixin source is missing @JsonMixin: " + mixinType.getName());
+ }
+ Class<?> target;
+ try {
+ target = declaration.target();
+ } catch (RuntimeException | LinkageError e) {
+ throw new IllegalArgumentException(
+ "Cannot resolve JSON Mixin target for " + mixinType.getName(), e);
+ }
+ mixins.put(target, mixinType);
+ return this;
+ }
+
/**
* Sets the JSON type checker. Pass {@code null} to allow all non-disallowed classes.
*
@@ -220,6 +260,7 @@ public final class ForyJsonBuilder {
concurrencyLevel,
bufferSizeLimitBytes,
codecRegistry,
+ mixins,
typeChecker));
}
}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java b/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java
index e4e4b91c4..fb665e0aa 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java
@@ -19,10 +19,17 @@
package org.apache.fory.json;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.fory.annotation.Internal;
import org.apache.fory.json.resolver.CodecRegistry;
/**
@@ -50,6 +57,7 @@ public final class JsonConfig {
private final int concurrencyLevel;
private final int bufferSizeLimitBytes;
private final CodecRegistry codecRegistry;
+ private final Map<Class<?>, Class<?>> mixins;
private final JsonTypeChecker typeChecker;
private final JsonTypeCheckContext typeCheckContext;
private final String codecRegistryKey;
@@ -68,6 +76,7 @@ public final class JsonConfig {
int concurrencyLevel,
int bufferSizeLimitBytes,
CodecRegistry codecRegistry,
+ Map<Class<?>, Class<?>> mixins,
JsonTypeChecker typeChecker) {
this.writeNullFields = writeNullFields;
this.codegenEnabled = codegenEnabled;
@@ -82,12 +91,17 @@ public final class JsonConfig {
this.concurrencyLevel = concurrencyLevel;
this.bufferSizeLimitBytes = bufferSizeLimitBytes;
this.codecRegistry = codecRegistry;
+ this.mixins = immutableMixins(mixins);
this.typeChecker = typeChecker;
typeCheckContext = new JsonTypeCheckContext();
codecRegistryKey = codecRegistry.codegenKey();
codegenKey =
new CodegenKey(
- writeNullFields, propertyDiscoveryEnabled, propertyNamingStrategy, codecRegistryKey);
+ writeNullFields,
+ propertyDiscoveryEnabled,
+ propertyNamingStrategy,
+ codecRegistryKey,
+ mixinKey(this.mixins));
}
public boolean writeNullFields() {
@@ -143,6 +157,12 @@ public final class JsonConfig {
return codecRegistry;
}
+ /** Returns the immutable exact target-to-Mixin registration snapshot. */
+ @Internal
+ public Map<Class<?>, Class<?>> mixins() {
+ return mixins;
+ }
+
public JsonTypeChecker typeChecker() {
return typeChecker;
}
@@ -171,7 +191,8 @@ public final class JsonConfig {
&& concurrencyLevel == that.concurrencyLevel
&& bufferSizeLimitBytes == that.bufferSizeLimitBytes
&& typeChecker == that.typeChecker
- && Objects.equals(codecRegistryKey, that.codecRegistryKey);
+ && Objects.equals(codecRegistryKey, that.codecRegistryKey)
+ && mixins.equals(that.mixins);
}
@Override
@@ -188,9 +209,36 @@ public final class JsonConfig {
result = 31 * result + bufferSizeLimitBytes;
result = 31 * result + System.identityHashCode(typeChecker);
result = 31 * result + codecRegistryKey.hashCode();
+ result = 31 * result + mixins.hashCode();
return result;
}
+ private static Map<Class<?>, Class<?>> immutableMixins(Map<Class<?>, Class<?>> registrations) {
+ if (registrations.isEmpty()) {
+ return Collections.emptyMap();
+ }
+ return Collections.unmodifiableMap(new IdentityHashMap<>(registrations));
+ }
+
+ private static String mixinKey(Map<Class<?>, Class<?>> mixins) {
+ if (mixins.isEmpty()) {
+ return "";
+ }
+ List<Map.Entry<Class<?>, Class<?>>> entries = new ArrayList<>(mixins.entrySet());
+ entries.sort(
+ Comparator.comparing((Map.Entry<Class<?>, Class<?>> entry) -> entry.getKey().getName())
+ .thenComparing(entry -> entry.getValue().getName()));
+ StringBuilder builder = new StringBuilder(entries.size() * 64);
+ for (Map.Entry<Class<?>, Class<?>> entry : entries) {
+ builder
+ .append(entry.getKey().getName())
+ .append('=')
+ .append(entry.getValue().getName())
+ .append(';');
+ }
+ return builder.toString();
+ }
+
private static final AtomicInteger COUNTER = new AtomicInteger(0);
// Equal generated source inputs share one map entry, following core generated-code naming model.
@@ -211,16 +259,19 @@ public final class JsonConfig {
private final boolean propertyDiscoveryEnabled;
private final PropertyNamingStrategy propertyNamingStrategy;
private final String codecRegistryKey;
+ private final String mixinKey;
private CodegenKey(
boolean writeNullFields,
boolean propertyDiscoveryEnabled,
PropertyNamingStrategy propertyNamingStrategy,
- String codecRegistryKey) {
+ String codecRegistryKey,
+ String mixinKey) {
this.writeNullFields = writeNullFields;
this.propertyDiscoveryEnabled = propertyDiscoveryEnabled;
this.propertyNamingStrategy = propertyNamingStrategy;
this.codecRegistryKey = codecRegistryKey;
+ this.mixinKey = mixinKey;
}
@Override
@@ -235,13 +286,16 @@ public final class JsonConfig {
return writeNullFields == that.writeNullFields
&& propertyDiscoveryEnabled == that.propertyDiscoveryEnabled
&& propertyNamingStrategy == that.propertyNamingStrategy
- && Objects.equals(codecRegistryKey, that.codecRegistryKey);
+ && Objects.equals(codecRegistryKey, that.codecRegistryKey)
+ && Objects.equals(mixinKey, that.mixinKey);
}
@Override
public int hashCode() {
- return Objects.hash(
- writeNullFields, propertyDiscoveryEnabled, propertyNamingStrategy, codecRegistryKey);
+ int result =
+ Objects.hash(
+ writeNullFields, propertyDiscoveryEnabled, propertyNamingStrategy, codecRegistryKey);
+ return 31 * result + mixinKey.hashCode();
}
}
}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonMixin.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonMixin.java
new file mode 100644
index 000000000..89e93a62c
--- /dev/null
+++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonMixin.java
@@ -0,0 +1,68 @@
+/*
+ * 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.annotation;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Declares the exact model class configured by this JSON annotation Mixin.
+ *
+ * <p>A Mixin source must be a named interface, top-level abstract class, or static abstract member
+ * class. It must not extend or implement another type and is never instantiated. Its directly
+ * declared annotated fields, methods, constructors, and parameters structurally select existing
+ * declarations on {@link #target()}. Target fields match by name and erased type, methods by name
+ * plus erased parameter and return types, constructors by erased parameter types, and parameters by
+ * executable and index. The target declaration continues to own its Java type, generic type,
+ * access, invocation, and value.
+ *
+ * <p>A Mixin may contribute {@link JsonAnyGetter}, {@link JsonAnyProperty}, {@link JsonAnySetter},
+ * {@link JsonBase64}, {@link JsonCodec}, {@link JsonCreator}, {@link JsonIgnore}, {@link
+ * JsonProperty}, {@link JsonPropertyOrder}, {@link JsonRawValue}, {@link JsonSubTypes}, {@link
+ * JsonUnwrapped}, and {@link JsonValue}. {@link JsonType} remains a marker declared directly on a
+ * model and cannot be contributed or removed by a Mixin. A contributed annotation completely
+ * replaces the target annotation of the same type at the matched declaration; annotation members
+ * are not merged individually. Use {@link JsonMixinRemove} for explicit removal.
+ *
+ * <p>A contributed {@link JsonCodec} follows the same codec resolution as a codec declared on the
+ * target. An exact codec registered with {@link
+ * org.apache.fory.json.ForyJsonBuilder#registerCodec(Class,
+ * org.apache.fory.json.codec.JsonValueCodec)} takes precedence, while an effective type-level
+ * {@code JsonCodec} takes precedence over the target's built-in JSON mapping.
+ *
+ * <p>Register a source with {@link org.apache.fory.json.ForyJsonBuilder#registerMixin(Class)}.
+ * Registration applies only to the exact declared target. Registering a second source for that
+ * target replaces the first source for subsequently built JSON runtimes. A source containing no
+ * mapping annotations is a no-op and therefore clears an earlier overlay when registered later for
+ * the same target.
+ */
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE)
+public @interface JsonMixin {
+ /**
+ * Returns the exact non-primitive, non-array, non-annotation model class configured by this
+ * source.
+ */
+ Class<?> target();
+}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonMixinRemove.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonMixinRemove.java
new file mode 100644
index 000000000..06ba6244f
--- /dev/null
+++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonMixinRemove.java
@@ -0,0 +1,57 @@
+/*
+ * 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.annotation;
+
+import java.lang.annotation.Annotation;
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Removes selected target annotations from one matched declaration in a JSON Mixin.
+ *
+ * <p>This annotation is valid only on a {@link JsonMixin} source. Each value must be a mapping
+ * annotation supported by {@link JsonMixin}, and that annotation's Java {@link Target} must permit
+ * the selector kind. {@link JsonType}, {@link JsonMixin}, {@code JsonMixinRemove}, and unrelated
+ * annotations cannot be removed. The list must be non-empty and contain no duplicates, and one
+ * source declaration cannot both contribute and remove the same annotation type.
+ *
+ * <p>Removal affects only the matched physical declaration in the exact target context before
+ * normal logical-property merging. Removing an absent annotation is allowed, which lets a
+ * type-level removal mask an inherited {@link JsonCodec} or {@link JsonPropertyOrder}. It never
+ * removes a field, method, constructor, parameter, or logical property.
+ *
+ * @see org.apache.fory.json.ForyJsonBuilder#registerMixin(Class)
+ */
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Target({
+ ElementType.TYPE,
+ ElementType.FIELD,
+ ElementType.METHOD,
+ ElementType.CONSTRUCTOR,
+ ElementType.PARAMETER
+})
+public @interface JsonMixinRemove {
+ /** Returns the Fory JSON annotation types removed from the matched target declaration. */
+ Class<? extends Annotation>[] value();
+}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonType.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonType.java
index 14f39756e..743b35957 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonType.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonType.java
@@ -40,8 +40,12 @@ import java.lang.annotation.Target;
* <p>This annotation does not change the JSON schema and is intentionally not inherited. An
* ordinary mutable class may omit it and use reflection, with application-authored exact R8 rules
* on Android. Android-desugared Records, including Records represented by {@link JsonValue},
- * require this annotation and the processor because Android does not expose the Java Record
- * reflection APIs.
+ * require processor-generated operations from either a direct {@code JsonType} declaration or an
+ * exact {@link JsonMixin} pair because Android does not expose the Java Record reflection APIs.
+ *
+ * <p>{@link JsonMixin} cannot contribute or remove this build-time marker. A non-empty Mixin is its
+ * own processor entry point and produces the platform configuration and generated operations
+ * required by its exact target/source mapping.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java
index c961f4dde..ace30ddc9 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java
@@ -44,6 +44,7 @@ import org.apache.fory.json.meta.JsonFieldTable;
import org.apache.fory.json.reader.Latin1JsonReader;
import org.apache.fory.json.reader.Utf16JsonReader;
import org.apache.fory.json.reader.Utf8JsonReader;
+import org.apache.fory.json.resolver.JsonSharedRegistry;
import org.apache.fory.json.resolver.JsonTypeInfo;
import org.apache.fory.json.resolver.JsonTypeResolver;
import org.apache.fory.json.writer.StringJsonWriter;
@@ -108,13 +109,19 @@ public class ObjectCodec<T> implements JsonValueCodec<T> {
boolean propertyDiscoveryEnabled,
PropertyNamingStrategy propertyNamingStrategy,
boolean writeNullFields,
+ JsonSharedRegistry sharedRegistry,
GeneratedJsonCodec<?> generatedCodec) {
- return ObjectCodecBuilder.build(
- ownerType,
- propertyDiscoveryEnabled,
- propertyNamingStrategy,
- writeNullFields,
- generatedCodec);
+ try {
+ return ObjectCodecBuilder.build(
+ ownerType,
+ propertyDiscoveryEnabled,
+ propertyNamingStrategy,
+ writeNullFields,
+ sharedRegistry,
+ generatedCodec);
+ } catch (ForyJsonException e) {
+ throw sharedRegistry.mixinSchemaFailure(ownerType.getRawType(), e);
+ }
}
static <T> ObjectCodec<T> createCodec(
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java
index 9eb185978..ce6998826 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java
@@ -61,6 +61,7 @@ import org.apache.fory.json.meta.JsonCreatorInfo;
import org.apache.fory.json.meta.JsonFieldAccessor;
import org.apache.fory.json.meta.JsonFieldInfo;
import org.apache.fory.json.meta.JsonFieldNameHash;
+import org.apache.fory.json.resolver.JsonSharedRegistry;
import org.apache.fory.reflect.ObjectInstantiator;
import org.apache.fory.reflect.ObjectInstantiators;
import org.apache.fory.reflect.TypeRef;
@@ -76,19 +77,23 @@ final class ObjectCodecBuilder {
boolean propertyDiscoveryEnabled,
PropertyNamingStrategy propertyNamingStrategy,
boolean writeNullFields,
+ JsonSharedRegistry sharedRegistry,
GeneratedJsonCodec<?> generatedCodec) {
Class<?> type = ownerType.getRawType();
+ Annotations annotations = new Annotations(type, sharedRegistry);
boolean record =
generatedCodec == null ? RecordUtils.isRecord(type) : generatedCodec.validatedRecord();
boolean hasAnyField =
- validateMemberAnnotations(type, propertyDiscoveryEnabled, record, generatedCodec);
+ validateMemberAnnotations(
+ type, propertyDiscoveryEnabled, record, generatedCodec, annotations);
LinkedHashMap<String, FieldBuilder> builders = new LinkedHashMap<>();
- addFields(type, record, propertyDiscoveryEnabled, hasAnyField, builders);
+ addFields(type, record, propertyDiscoveryEnabled, hasAnyField, builders, annotations);
if (record) {
addRecordAccessors(type, builders, generatedCodec);
}
Method anySetter =
- addJsonMethods(type, propertyDiscoveryEnabled, record, builders, generatedCodec);
+ addJsonMethods(
+ type, propertyDiscoveryEnabled, record, builders, generatedCodec, annotations);
if (generatedCodec != null && generatedCodec.hasAnySetter() && anySetter == null) {
throw new ForyJsonException(
"Generated JSON Any setter does not match runtime annotations on " + type.getName());
@@ -116,14 +121,15 @@ final class ObjectCodecBuilder {
JsonCreatorInfo creatorInfo =
record
? buildRecordCreatorInfo(
- type, ownerType, builders, propertyNamingStrategy, generatedCodec)
+ type, ownerType, builders, propertyNamingStrategy, generatedCodec, annotations)
: buildCreatorInfo(
type,
ownerType,
builders,
propertyNamingStrategy,
creatorOnlyUnwrapped,
- generatedCodec);
+ generatedCodec,
+ annotations);
if (anySetter != null && (record || creatorInfo != null)) {
throw new ForyJsonException(
"@JsonAnySetter is not supported on constructor-backed type " + type.getName());
@@ -135,7 +141,7 @@ final class ObjectCodecBuilder {
throw new ForyJsonException(
"Read-enabled @JsonAnyProperty must bind one @JsonCreator argument on " + type.getName());
}
- JsonPropertyOrder propertyOrder = findPropertyOrder(type);
+ JsonPropertyOrder propertyOrder = findPropertyOrder(type, annotations);
boolean hasAny = anyBuilder != null || anySetter != null;
boolean hasUnwrapped = !creatorOnlyUnwrapped.isEmpty() || hasUnwrappedProperty(builders);
boolean anyWrites = anyBuilder != null && anyBuilder.anyWriteEnabled();
@@ -317,7 +323,13 @@ final class ObjectCodecBuilder {
AnyInfo anyInfo =
hasAny
? buildAnyInfo(
- ownerType, anyBuilder, anySetter, anyWriteIndex, constructionIndex, generatedCodec)
+ ownerType,
+ anyBuilder,
+ anySetter,
+ anyWriteIndex,
+ constructionIndex,
+ generatedCodec,
+ annotations)
: null;
ObjectInstantiator<?> instantiator =
creatorInfo == null ? ObjectInstantiators.createObjectInstantiator(type) : null;
@@ -347,11 +359,11 @@ final class ObjectCodecBuilder {
return false;
}
- private static JsonPropertyOrder findPropertyOrder(Class<?> type) {
+ private static JsonPropertyOrder findPropertyOrder(Class<?> type, Annotations annotations) {
for (Class<?> current = type;
current != null && current != Object.class;
current = current.getSuperclass()) {
- JsonPropertyOrder order = current.getDeclaredAnnotation(JsonPropertyOrder.class);
+ JsonPropertyOrder order = annotations.get(current, JsonPropertyOrder.class);
if (order != null) {
return order;
}
@@ -751,7 +763,8 @@ final class ObjectCodecBuilder {
boolean record,
boolean propertyDiscoveryEnabled,
boolean hasAnyField,
- LinkedHashMap<String, FieldBuilder> builders) {
+ LinkedHashMap<String, FieldBuilder> builders,
+ Annotations annotations) {
List<Class<?>> hierarchy = new ArrayList<>();
for (Class<?> current = type;
current != null && current != Object.class;
@@ -764,22 +777,26 @@ final class ObjectCodecBuilder {
for (int i = hierarchy.size() - 1; i >= 0; i--) {
Class<?> current = hierarchy.get(i);
for (Field field : current.getDeclaredFields()) {
- if (field.isAnnotationPresent(JsonUnwrapped.class) && !isEligibleField(field)) {
+ if (annotations.has(field, JsonUnwrapped.class) && !isEligibleField(field)) {
throw new ForyJsonException("@JsonUnwrapped is not supported on JSON field: " + field);
}
int modifiers = field.getModifiers();
if (!isEligibleField(field)) {
continue;
}
- JsonIgnore ignore = field.getAnnotation(JsonIgnore.class);
+ JsonIgnore ignore = annotations.get(field, JsonIgnore.class);
boolean write = ignore == null || !ignore.ignoreWrite();
boolean readAllowed = ignore == null || !ignore.ignoreRead();
- boolean any = field.isAnnotationPresent(JsonAnyProperty.class);
+ boolean any = annotations.has(field, JsonAnyProperty.class);
boolean read = (any || record || !Modifier.isFinal(modifiers)) && readAllowed;
if (!retainIgnoredFields && !write && !read && !any) {
continue;
}
- FieldBuilder builder = builders.computeIfAbsent(field.getName(), FieldBuilder::new);
+ FieldBuilder builder = builders.get(field.getName());
+ if (builder == null) {
+ builder = new FieldBuilder(field.getName(), annotations);
+ builders.put(field.getName(), builder);
+ }
builder.setField(type, field, write, read, write, readAllowed);
}
}
@@ -790,7 +807,8 @@ final class ObjectCodecBuilder {
boolean propertyDiscoveryEnabled,
boolean record,
LinkedHashMap<String, FieldBuilder> builders,
- GeneratedJsonCodec<?> generatedCodec) {
+ GeneratedJsonCodec<?> generatedCodec,
+ Annotations annotations) {
Method anyGetter = null;
Method anySetter = null;
for (Method method : type.getMethods()) {
@@ -799,12 +817,11 @@ final class ObjectCodecBuilder {
if (method.isSynthetic() || method.isBridge()) {
continue;
}
- if (method.getDeclaringClass().isInterface()
- && method.isAnnotationPresent(JsonProperty.class)) {
+ if (method.getDeclaringClass().isInterface() && annotations.has(method, JsonProperty.class)) {
validatePropertyMethod(type, method, propertyDiscoveryEnabled, record, generatedCodec);
}
- JsonAnyGetter getter = method.getAnnotation(JsonAnyGetter.class);
- JsonAnySetter setter = method.getAnnotation(JsonAnySetter.class);
+ JsonAnyGetter getter = annotations.get(method, JsonAnyGetter.class);
+ JsonAnySetter setter = annotations.get(method, JsonAnySetter.class);
if (getter != null || setter != null) {
if (!propertyDiscoveryEnabled) {
throw new ForyJsonException(
@@ -820,7 +837,7 @@ final class ObjectCodecBuilder {
}
anyGetter = method;
} else {
- validateAnySetter(method);
+ validateAnySetter(method, annotations);
if (anySetter != null) {
throw new ForyJsonException("Multiple @JsonAnySetter methods on " + type.getName());
}
@@ -834,7 +851,7 @@ final class ObjectCodecBuilder {
if (propertyName != null) {
FieldBuilder builder = builders.get(propertyName);
if (builder == null) {
- builder = new FieldBuilder(propertyName);
+ builder = new FieldBuilder(propertyName, annotations);
builders.put(propertyName, builder);
}
builder.setWriteGetter(type, method);
@@ -844,7 +861,7 @@ final class ObjectCodecBuilder {
if (propertyName != null) {
FieldBuilder builder = builders.get(propertyName);
if (builder == null) {
- builder = new FieldBuilder(propertyName);
+ builder = new FieldBuilder(propertyName, annotations);
builders.put(propertyName, builder);
}
builder.setReadSetter(type, method);
@@ -857,7 +874,7 @@ final class ObjectCodecBuilder {
}
FieldBuilder builder = builders.get(propertyName);
if (builder == null) {
- builder = new FieldBuilder(propertyName);
+ builder = new FieldBuilder(propertyName, annotations);
builders.put(propertyName, builder);
}
builder.setAnyGetter(type, anyGetter);
@@ -956,14 +973,14 @@ final class ObjectCodecBuilder {
}
}
- private static void rejectRecordCreator(Class<?> type) {
+ private static void rejectRecordCreator(Class<?> type, Annotations annotations) {
for (Constructor<?> constructor : type.getDeclaredConstructors()) {
- if (constructor.isAnnotationPresent(JsonCreator.class)) {
+ if (annotations.has(constructor, JsonCreator.class)) {
throw new ForyJsonException("@JsonCreator is not supported on record " + type.getName());
}
}
for (Method method : type.getDeclaredMethods()) {
- if (method.isAnnotationPresent(JsonCreator.class)) {
+ if (annotations.has(method, JsonCreator.class)) {
throw new ForyJsonException("@JsonCreator is not supported on record " + type.getName());
}
}
@@ -974,8 +991,9 @@ final class ObjectCodecBuilder {
TypeRef<?> ownerType,
LinkedHashMap<String, FieldBuilder> builders,
PropertyNamingStrategy namingStrategy,
- GeneratedJsonCodec<?> generatedCodec) {
- rejectRecordCreator(type);
+ GeneratedJsonCodec<?> generatedCodec,
+ Annotations annotations) {
+ rejectRecordCreator(type, annotations);
String[] names;
Class<?>[] rawTypes;
Constructor<?> constructor;
@@ -1047,8 +1065,9 @@ final class ObjectCodecBuilder {
LinkedHashMap<String, FieldBuilder> builders,
PropertyNamingStrategy namingStrategy,
List<Declaration> creatorOnlyUnwrapped,
- GeneratedJsonCodec<?> generatedCodec) {
- JsonCreatorDeclaration declaration = JsonCreatorDeclaration.find(type);
+ GeneratedJsonCodec<?> generatedCodec,
+ Annotations annotations) {
+ JsonCreatorDeclaration declaration = JsonCreatorDeclaration.find(type, annotations.registry);
if (declaration == null) {
if (generatedCodec != null && generatedCodec.validatedCreatorParameterNames() != null) {
throw new ForyJsonException(
@@ -1058,7 +1077,7 @@ final class ObjectCodecBuilder {
}
Executable creator = declaration.executable();
JsonCreator annotation = declaration.annotation();
- validateGeneratedCreator(type, creator, annotation, generatedCodec);
+ validateGeneratedCreator(type, creator, annotation, generatedCodec, annotations);
Map<String, FieldBuilder> jsonProperties = new LinkedHashMap<>();
for (FieldBuilder builder : builders.values()) {
@@ -1096,7 +1115,7 @@ final class ObjectCodecBuilder {
if (javaName.isEmpty() || !names.add(javaName)) {
throw new ForyJsonException("Invalid @JsonCreator property name " + javaName);
}
- if (parameters[i].isAnnotationPresent(JsonProperty.class)) {
+ if (annotations.has(parameters[i], JsonProperty.class)) {
throw new ForyJsonException(
"Property-list @JsonCreator parameters cannot declare @JsonProperty: " + creator);
}
@@ -1131,7 +1150,7 @@ final class ObjectCodecBuilder {
} else {
Set<String> names = new HashSet<>();
for (int i = 0; i < parameters.length; i++) {
- JsonProperty property = parameters[i].getAnnotation(JsonProperty.class);
+ JsonProperty property = annotations.get(parameters[i], JsonProperty.class);
if (property == null || property.value().isEmpty()) {
throw new ForyJsonException(
"Parameter-local @JsonCreator requires a non-empty @JsonProperty on every parameter: "
@@ -1178,13 +1197,13 @@ final class ObjectCodecBuilder {
Type resolved = ownerType.resolveType(parameterTypes[i]).getType();
JsonCodec codecAnnotation =
builder == null
- ? parameters[i].getAnnotation(JsonCodec.class)
+ ? annotations.get(parameters[i], JsonCodec.class)
: builder.codecAnnotation();
Class<? extends JsonValueCodec<?>> valueCodecClass =
builder == null ? null : builder.valueCodecClass();
JsonUnwrapped unwrapped =
builder == null
- ? parameters[i].getAnnotation(JsonUnwrapped.class)
+ ? annotations.get(parameters[i], JsonUnwrapped.class)
: builder.unwrappedAnnotation;
if (unwrapped != null) {
if (codecAnnotation != null || valueCodecClass != null) {
@@ -1222,7 +1241,8 @@ final class ObjectCodecBuilder {
Class<?> type,
Executable creator,
JsonCreator annotation,
- GeneratedJsonCodec<?> generatedCodec) {
+ GeneratedJsonCodec<?> generatedCodec,
+ Annotations annotations) {
if (generatedCodec == null) {
return;
}
@@ -1242,7 +1262,7 @@ final class ObjectCodecBuilder {
runtimeNames = new String[creator.getParameterCount()];
Parameter[] parameters = creator.getParameters();
for (int i = 0; i < parameters.length; i++) {
- JsonProperty property = parameters[i].getAnnotation(JsonProperty.class);
+ JsonProperty property = annotations.get(parameters[i], JsonProperty.class);
runtimeNames[i] = property == null ? null : property.value();
}
}
@@ -1331,39 +1351,38 @@ final class ObjectCodecBuilder {
Class<?> type,
boolean propertyDiscoveryEnabled,
boolean record,
- GeneratedJsonCodec<?> generatedCodec) {
+ GeneratedJsonCodec<?> generatedCodec,
+ Annotations annotations) {
boolean hasAnyField = false;
- for (Class<?> current = type;
- current != null && current != Object.class;
- current = current.getSuperclass()) {
+ for (Class<?> current = type; current != null; current = current.getSuperclass()) {
for (Field field : current.getDeclaredFields()) {
- if (field.isAnnotationPresent(JsonBase64.class)) {
- validateBase64Field(field);
+ if (annotations.has(field, JsonBase64.class)) {
+ validateBase64Field(field, annotations);
}
- if (field.isAnnotationPresent(JsonRawValue.class)) {
- validateRawField(field);
+ if (annotations.has(field, JsonRawValue.class)) {
+ validateRawField(field, annotations);
}
- if (field.isAnnotationPresent(JsonCodec.class) && !isEligibleField(field)) {
+ if (annotations.has(field, JsonCodec.class) && !isEligibleField(field)) {
throw new ForyJsonException("@JsonCodec is not supported on JSON field: " + field);
}
- JsonIgnore ignore = field.getAnnotation(JsonIgnore.class);
- if (field.isAnnotationPresent(JsonUnwrapped.class)
+ JsonIgnore ignore = annotations.get(field, JsonIgnore.class);
+ if (annotations.has(field, JsonUnwrapped.class)
&& ignore != null
&& ignore.ignoreRead()
&& ignore.ignoreWrite()) {
throw new ForyJsonException(
"@JsonUnwrapped has no JSON read or write direction: " + field);
}
- if (field.isAnnotationPresent(JsonCodec.class)
+ if (annotations.has(field, JsonCodec.class)
&& ignore != null
&& ignore.ignoreRead()
&& ignore.ignoreWrite()) {
throw new ForyJsonException("@JsonCodec has no JSON read or write direction: " + field);
}
- if (field.isAnnotationPresent(JsonProperty.class) && !isEligibleField(field)) {
+ if (annotations.has(field, JsonProperty.class) && !isEligibleField(field)) {
throw new ForyJsonException("@JsonProperty is not supported on JSON field: " + field);
}
- if (field.isAnnotationPresent(JsonAnyProperty.class)) {
+ if (annotations.has(field, JsonAnyProperty.class)) {
if (!isEligibleField(field)) {
throw new ForyJsonException(
"@JsonAnyProperty is not supported on JSON field: " + field);
@@ -1380,36 +1399,40 @@ final class ObjectCodecBuilder {
if (isOverridden(type, method)) {
continue;
}
- if (method.isAnnotationPresent(JsonCodec.class)) {
- validateCodecMethod(type, method, propertyDiscoveryEnabled, record, generatedCodec);
+ if (annotations.has(method, JsonCodec.class)) {
+ validateCodecMethod(
+ type, method, propertyDiscoveryEnabled, record, generatedCodec, annotations);
}
- validateCodecParameters(method, propertyDiscoveryEnabled, record);
- if (method.isAnnotationPresent(JsonRawValue.class)) {
- validateRawMethod(type, method, propertyDiscoveryEnabled, record, generatedCodec);
+ validateCodecParameters(method, propertyDiscoveryEnabled, record, annotations);
+ if (annotations.has(method, JsonRawValue.class)) {
+ validateRawMethod(
+ type, method, propertyDiscoveryEnabled, record, generatedCodec, annotations);
}
- if (method.isAnnotationPresent(JsonBase64.class)) {
- validateBase64Method(type, method, propertyDiscoveryEnabled, record, generatedCodec);
+ if (annotations.has(method, JsonBase64.class)) {
+ validateBase64Method(
+ type, method, propertyDiscoveryEnabled, record, generatedCodec, annotations);
}
- if (method.isAnnotationPresent(JsonUnwrapped.class)) {
- validateUnwrappedMethod(type, method, propertyDiscoveryEnabled, record, generatedCodec);
+ if (annotations.has(method, JsonUnwrapped.class)) {
+ validateUnwrappedMethod(
+ type, method, propertyDiscoveryEnabled, record, generatedCodec, annotations);
}
- validateUnwrappedParameters(type, method, propertyDiscoveryEnabled, record);
- if (method.isAnnotationPresent(JsonProperty.class)) {
+ validateUnwrappedParameters(type, method, propertyDiscoveryEnabled, record, annotations);
+ if (annotations.has(method, JsonProperty.class)) {
validatePropertyMethod(type, method, propertyDiscoveryEnabled, record, generatedCodec);
}
- if (method.isAnnotationPresent(JsonAnyGetter.class)) {
+ if (annotations.has(method, JsonAnyGetter.class)) {
if (!propertyDiscoveryEnabled) {
throw new ForyJsonException(
"JSON Any method annotations require property discovery: " + method);
}
validateAnyGetter(method);
}
- if (method.isAnnotationPresent(JsonAnySetter.class)) {
+ if (annotations.has(method, JsonAnySetter.class)) {
if (!propertyDiscoveryEnabled) {
throw new ForyJsonException(
"JSON Any method annotations require property discovery: " + method);
}
- validateAnySetter(method);
+ validateAnySetter(method, annotations);
}
}
}
@@ -1417,30 +1440,34 @@ final class ObjectCodecBuilder {
// and accessors. Do not re-read desugared constructor parameters: Android 8 ART may crash.
if (!record || generatedCodec == null) {
for (Constructor<?> constructor : type.getDeclaredConstructors()) {
- validateCodecParameters(type, constructor, record);
- validateUnwrappedParameters(type, constructor, record);
+ validateCodecParameters(type, constructor, record, annotations);
+ validateUnwrappedParameters(type, constructor, record, annotations);
}
}
for (Method method : type.getMethods()) {
if (!method.getDeclaringClass().isInterface()) {
continue;
}
- if (method.isAnnotationPresent(JsonCodec.class)) {
+ if (annotations.has(method, JsonCodec.class)) {
// getMethods exposes only the effective inherited declaration. A class or child-interface
// override therefore suppresses an annotation from the overridden interface method.
- validateCodecMethod(type, method, propertyDiscoveryEnabled, record, generatedCodec);
+ validateCodecMethod(
+ type, method, propertyDiscoveryEnabled, record, generatedCodec, annotations);
}
- validateCodecParameters(method, propertyDiscoveryEnabled, record);
- if (method.isAnnotationPresent(JsonRawValue.class)) {
- validateRawMethod(type, method, propertyDiscoveryEnabled, record, generatedCodec);
+ validateCodecParameters(method, propertyDiscoveryEnabled, record, annotations);
+ if (annotations.has(method, JsonRawValue.class)) {
+ validateRawMethod(
+ type, method, propertyDiscoveryEnabled, record, generatedCodec, annotations);
}
- if (method.isAnnotationPresent(JsonBase64.class)) {
- validateBase64Method(type, method, propertyDiscoveryEnabled, record, generatedCodec);
+ if (annotations.has(method, JsonBase64.class)) {
+ validateBase64Method(
+ type, method, propertyDiscoveryEnabled, record, generatedCodec, annotations);
}
- if (method.isAnnotationPresent(JsonUnwrapped.class)) {
- validateUnwrappedMethod(type, method, propertyDiscoveryEnabled, record, generatedCodec);
+ if (annotations.has(method, JsonUnwrapped.class)) {
+ validateUnwrappedMethod(
+ type, method, propertyDiscoveryEnabled, record, generatedCodec, annotations);
}
- validateUnwrappedParameters(type, method, propertyDiscoveryEnabled, record);
+ validateUnwrappedParameters(type, method, propertyDiscoveryEnabled, record, annotations);
}
return hasAnyField;
}
@@ -1450,13 +1477,14 @@ final class ObjectCodecBuilder {
Method method,
boolean propertyDiscoveryEnabled,
boolean record,
- GeneratedJsonCodec<?> generatedCodec) {
- if (method.isAnnotationPresent(JsonAnyGetter.class)
- || method.isAnnotationPresent(JsonAnySetter.class)) {
+ GeneratedJsonCodec<?> generatedCodec,
+ Annotations annotations) {
+ if (annotations.has(method, JsonAnyGetter.class)
+ || annotations.has(method, JsonAnySetter.class)) {
throw new ForyJsonException("@JsonUnwrapped cannot annotate a JSON Any method: " + method);
}
if (record) {
- if (isPropagatedRecordUnwrapped(type, method, generatedCodec)) {
+ if (isPropagatedRecordUnwrapped(type, method, generatedCodec, annotations)) {
return;
}
throw new ForyJsonException("@JsonUnwrapped requires a record component accessor: " + method);
@@ -1470,13 +1498,17 @@ final class ObjectCodecBuilder {
}
private static void validateUnwrappedParameters(
- Class<?> type, Method method, boolean propertyDiscoveryEnabled, boolean record) {
+ Class<?> type,
+ Method method,
+ boolean propertyDiscoveryEnabled,
+ boolean record,
+ Annotations annotations) {
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
- if (!parameters[i].isAnnotationPresent(JsonUnwrapped.class)) {
+ if (!annotations.has(parameters[i], JsonUnwrapped.class)) {
continue;
}
- if (method.isAnnotationPresent(JsonCreator.class)) {
+ if (annotations.has(method, JsonCreator.class)) {
continue;
}
if (!record
@@ -1492,14 +1524,14 @@ final class ObjectCodecBuilder {
}
private static void validateUnwrappedParameters(
- Class<?> type, Constructor<?> constructor, boolean record) {
+ Class<?> type, Constructor<?> constructor, boolean record, Annotations annotations) {
Parameter[] parameters = constructor.getParameters();
for (int i = 0; i < parameters.length; i++) {
- JsonUnwrapped annotation = parameters[i].getAnnotation(JsonUnwrapped.class);
- if (annotation == null || constructor.isAnnotationPresent(JsonCreator.class)) {
+ JsonUnwrapped annotation = annotations.get(parameters[i], JsonUnwrapped.class);
+ if (annotation == null || annotations.has(constructor, JsonCreator.class)) {
continue;
}
- if (record && isPropagatedRecordUnwrapped(type, constructor, i, annotation)) {
+ if (record && isPropagatedRecordUnwrapped(type, constructor, i, annotation, annotations)) {
continue;
}
throw new ForyJsonException(
@@ -1512,8 +1544,9 @@ final class ObjectCodecBuilder {
Method method,
boolean propertyDiscoveryEnabled,
boolean record,
- GeneratedJsonCodec<?> generatedCodec) {
- if (method.isAnnotationPresent(JsonAnyGetter.class)) {
+ GeneratedJsonCodec<?> generatedCodec,
+ Annotations annotations) {
+ if (annotations.has(method, JsonAnyGetter.class)) {
if (!propertyDiscoveryEnabled) {
throw new ForyJsonException(
"JSON Any method annotations require property discovery: " + method);
@@ -1537,16 +1570,16 @@ final class ObjectCodecBuilder {
}
private static void validateCodecParameters(
- Method method, boolean propertyDiscoveryEnabled, boolean record) {
+ Method method, boolean propertyDiscoveryEnabled, boolean record, Annotations annotations) {
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
- if (!parameters[i].isAnnotationPresent(JsonCodec.class)) {
+ if (!annotations.has(parameters[i], JsonCodec.class)) {
continue;
}
- if (method.isAnnotationPresent(JsonCreator.class)) {
+ if (annotations.has(method, JsonCreator.class)) {
continue;
}
- if (method.isAnnotationPresent(JsonAnySetter.class)) {
+ if (annotations.has(method, JsonAnySetter.class)) {
if (propertyDiscoveryEnabled && i == 1) {
continue;
}
@@ -1566,11 +1599,11 @@ final class ObjectCodecBuilder {
}
private static void validateCodecParameters(
- Class<?> type, Constructor<?> constructor, boolean record) {
+ Class<?> type, Constructor<?> constructor, boolean record, Annotations annotations) {
Parameter[] parameters = constructor.getParameters();
for (int i = 0; i < parameters.length; i++) {
- JsonCodec annotation = parameters[i].getAnnotation(JsonCodec.class);
- if (annotation == null || constructor.isAnnotationPresent(JsonCreator.class)) {
+ JsonCodec annotation = annotations.get(parameters[i], JsonCodec.class);
+ if (annotation == null || annotations.has(constructor, JsonCreator.class)) {
continue;
}
if (record && isRecordConstructor(type, constructor)) {
@@ -1580,16 +1613,16 @@ final class ObjectCodecBuilder {
}
}
- private static void validateRawField(Field field) {
+ private static void validateRawField(Field field, Annotations annotations) {
if (!isEligibleField(field) || field.getType() != String.class) {
throw new ForyJsonException("Invalid @JsonRawValue field " + field);
}
- if (field.isAnnotationPresent(JsonCodec.class)
- || field.isAnnotationPresent(JsonBase64.class)
- || field.isAnnotationPresent(JsonAnyProperty.class)) {
+ if (annotations.has(field, JsonCodec.class)
+ || annotations.has(field, JsonBase64.class)
+ || annotations.has(field, JsonAnyProperty.class)) {
throw new ForyJsonException("Conflicting JSON annotations on @JsonRawValue field " + field);
}
- JsonIgnore ignore = field.getAnnotation(JsonIgnore.class);
+ JsonIgnore ignore = annotations.get(field, JsonIgnore.class);
if (ignore != null && ignore.ignoreRead() && ignore.ignoreWrite()) {
throw new ForyJsonException("@JsonRawValue has no JSON read or write direction: " + field);
}
@@ -1600,37 +1633,39 @@ final class ObjectCodecBuilder {
Method method,
boolean propertyDiscoveryEnabled,
boolean record,
- GeneratedJsonCodec<?> generatedCodec) {
+ GeneratedJsonCodec<?> generatedCodec,
+ Annotations annotations) {
if ((!propertyDiscoveryEnabled
&& !(record
- && isPropagatedRecordAnnotation(type, method, JsonRawValue.class, generatedCodec)))
+ && isPropagatedRecordAnnotation(
+ type, method, JsonRawValue.class, generatedCodec, annotations)))
|| !isEligibleAccessor(method)
|| method.isVarArgs()
|| method.getTypeParameters().length != 0
|| method.getParameterCount() != 0
|| method.getReturnType() != String.class
- || (!method.isAnnotationPresent(JsonValue.class)
+ || (!annotations.has(method, JsonValue.class)
&& ((!record && getterPropertyName(method) == null)
|| (record && !isRecordAccessor(type, method, generatedCodec))))) {
throw new ForyJsonException("Invalid @JsonRawValue method " + method);
}
- if (method.isAnnotationPresent(JsonCodec.class)
- || method.isAnnotationPresent(JsonBase64.class)
- || method.isAnnotationPresent(JsonAnyGetter.class)) {
+ if (annotations.has(method, JsonCodec.class)
+ || annotations.has(method, JsonBase64.class)
+ || annotations.has(method, JsonAnyGetter.class)) {
throw new ForyJsonException("Conflicting JSON annotations on @JsonRawValue method " + method);
}
}
- private static void validateBase64Field(Field field) {
+ private static void validateBase64Field(Field field, Annotations annotations) {
if (!isEligibleField(field) || field.getType() != byte[].class) {
throw new ForyJsonException("Invalid @JsonBase64 field " + field);
}
- if (field.isAnnotationPresent(JsonCodec.class)
- || field.isAnnotationPresent(JsonRawValue.class)
- || field.isAnnotationPresent(JsonAnyProperty.class)) {
+ if (annotations.has(field, JsonCodec.class)
+ || annotations.has(field, JsonRawValue.class)
+ || annotations.has(field, JsonAnyProperty.class)) {
throw new ForyJsonException("Conflicting JSON annotations on @JsonBase64 field " + field);
}
- JsonIgnore ignore = field.getAnnotation(JsonIgnore.class);
+ JsonIgnore ignore = annotations.get(field, JsonIgnore.class);
if (ignore != null && ignore.ignoreRead() && ignore.ignoreWrite()) {
throw new ForyJsonException("@JsonBase64 has no JSON read or write direction: " + field);
}
@@ -1641,10 +1676,12 @@ final class ObjectCodecBuilder {
Method method,
boolean propertyDiscoveryEnabled,
boolean record,
- GeneratedJsonCodec<?> generatedCodec) {
+ GeneratedJsonCodec<?> generatedCodec,
+ Annotations annotations) {
if ((!propertyDiscoveryEnabled
&& !(record
- && isPropagatedRecordAnnotation(type, method, JsonBase64.class, generatedCodec)))
+ && isPropagatedRecordAnnotation(
+ type, method, JsonBase64.class, generatedCodec, annotations)))
|| !isEligibleAccessor(method)
|| method.isVarArgs()
|| method.getTypeParameters().length != 0
@@ -1654,9 +1691,9 @@ final class ObjectCodecBuilder {
|| (record && !isRecordAccessor(type, method, generatedCodec)))) {
throw new ForyJsonException("Invalid @JsonBase64 method " + method);
}
- if (method.isAnnotationPresent(JsonCodec.class)
- || method.isAnnotationPresent(JsonRawValue.class)
- || method.isAnnotationPresent(JsonAnyGetter.class)) {
+ if (annotations.has(method, JsonCodec.class)
+ || annotations.has(method, JsonRawValue.class)
+ || annotations.has(method, JsonAnyGetter.class)) {
throw new ForyJsonException("Conflicting JSON annotations on @JsonBase64 method " + method);
}
}
@@ -1679,12 +1716,13 @@ final class ObjectCodecBuilder {
Class<?> type,
Method method,
Class<? extends Annotation> annotationType,
- GeneratedJsonCodec<?> generatedCodec) {
+ GeneratedJsonCodec<?> generatedCodec,
+ Annotations annotations) {
if (!isRecordAccessor(type, method, generatedCodec)) {
return false;
}
try {
- return type.getDeclaredField(method.getName()).isAnnotationPresent(annotationType);
+ return annotations.has(type.getDeclaredField(method.getName()), annotationType);
} catch (NoSuchFieldException e) {
return false;
} catch (RuntimeException | LinkageError e) {
@@ -1694,14 +1732,14 @@ final class ObjectCodecBuilder {
}
private static boolean isPropagatedRecordUnwrapped(
- Class<?> type, Method method, GeneratedJsonCodec<?> generatedCodec) {
+ Class<?> type, Method method, GeneratedJsonCodec<?> generatedCodec, Annotations annotations) {
if (!isRecordAccessor(type, method, generatedCodec)) {
return false;
}
try {
JsonUnwrapped fieldAnnotation =
- type.getDeclaredField(method.getName()).getAnnotation(JsonUnwrapped.class);
- JsonUnwrapped methodAnnotation = method.getAnnotation(JsonUnwrapped.class);
+ annotations.get(type.getDeclaredField(method.getName()), JsonUnwrapped.class);
+ JsonUnwrapped methodAnnotation = annotations.get(method, JsonUnwrapped.class);
return sameUnwrapped(fieldAnnotation, methodAnnotation);
} catch (NoSuchFieldException e) {
return false;
@@ -1711,7 +1749,11 @@ final class ObjectCodecBuilder {
}
private static boolean isPropagatedRecordUnwrapped(
- Class<?> type, Constructor<?> constructor, int parameterIndex, JsonUnwrapped annotation) {
+ Class<?> type,
+ Constructor<?> constructor,
+ int parameterIndex,
+ JsonUnwrapped annotation,
+ Annotations annotations) {
if (!isRecordConstructor(type, constructor)) {
return false;
}
@@ -1721,8 +1763,8 @@ final class ObjectCodecBuilder {
}
try {
JsonUnwrapped fieldAnnotation =
- type.getDeclaredField(components[parameterIndex].getName())
- .getAnnotation(JsonUnwrapped.class);
+ annotations.get(
+ type.getDeclaredField(components[parameterIndex].getName()), JsonUnwrapped.class);
return sameUnwrapped(annotation, fieldAnnotation);
} catch (NoSuchFieldException e) {
return false;
@@ -1764,7 +1806,7 @@ final class ObjectCodecBuilder {
}
}
- private static void validateAnySetter(Method method) {
+ private static void validateAnySetter(Method method, Annotations annotations) {
int modifiers = method.getModifiers();
if (!Modifier.isPublic(modifiers)
|| Modifier.isStatic(modifiers)
@@ -1775,7 +1817,7 @@ final class ObjectCodecBuilder {
|| method.getReturnType() != void.class
|| method.getParameterCount() != 2
|| method.getParameterTypes()[0] != String.class
- || method.isAnnotationPresent(JsonProperty.class)) {
+ || annotations.has(method, JsonProperty.class)) {
throw new ForyJsonException("Invalid @JsonAnySetter method " + method);
}
}
@@ -1884,7 +1926,8 @@ final class ObjectCodecBuilder {
Method anySetter,
int writeIndex,
int constructionIndex,
- GeneratedJsonCodec<?> generatedCodec) {
+ GeneratedJsonCodec<?> generatedCodec,
+ Annotations annotations) {
Field anyField = builder == null ? null : builder.anyField;
Method writeGetter = builder == null || !builder.anyWriteEnabled() ? null : builder.writeGetter;
Field writeField =
@@ -1930,10 +1973,10 @@ final class ObjectCodecBuilder {
valueType = setterType;
valueRawType = setterRawType;
}
- if (anySetter.getParameters()[0].isAnnotationPresent(JsonCodec.class)) {
+ if (annotations.has(anySetter.getParameters()[0], JsonCodec.class)) {
throw new ForyJsonException("@JsonCodec is not supported on a JSON Any setter key");
}
- valueCodecAnnotation = anySetter.getParameters()[1].getAnnotation(JsonCodec.class);
+ valueCodecAnnotation = annotations.get(anySetter.getParameters()[1], JsonCodec.class);
if (valueCodecClass != null && valueCodecAnnotation != null) {
if (!isCompleteValueCodec(valueCodecAnnotation)
|| valueCodecAnnotation.value() != valueCodecClass) {
@@ -2089,8 +2132,28 @@ final class ObjectCodecBuilder {
return Character.class;
}
+ /** Target-bound cold annotation view; never retained by published codec metadata. */
+ private static final class Annotations {
+ private final Class<?> targetType;
+ private final JsonSharedRegistry registry;
+
+ private Annotations(Class<?> targetType, JsonSharedRegistry registry) {
+ this.targetType = targetType;
+ this.registry = registry;
+ }
+
+ private <A extends Annotation> A get(AnnotatedElement element, Class<A> annotationType) {
+ return registry.annotation(targetType, element, annotationType);
+ }
+
+ private boolean has(AnnotatedElement element, Class<? extends Annotation> annotationType) {
+ return get(element, annotationType) != null;
+ }
+ }
+
private static final class FieldBuilder {
private final String name;
+ private final Annotations annotations;
private Field field;
private boolean fieldWriteAllowed;
private boolean fieldReadAllowed;
@@ -2118,8 +2181,9 @@ final class ObjectCodecBuilder {
private JsonUnwrapped unwrappedAnnotation;
private AnnotatedElement unwrappedSource;
- private FieldBuilder(String name) {
+ private FieldBuilder(String name, Annotations annotations) {
this.name = name;
+ this.annotations = annotations;
}
private void setField(
@@ -2142,7 +2206,7 @@ final class ObjectCodecBuilder {
readField = field;
}
mergeAnnotation(type, field);
- if (field.isAnnotationPresent(JsonAnyProperty.class)) {
+ if (annotations.has(field, JsonAnyProperty.class)) {
if (!writeSource && !readSink) {
throw new ForyJsonException("@JsonAnyProperty must enable reading or writing: " + field);
}
@@ -2401,11 +2465,11 @@ final class ObjectCodecBuilder {
private void mergeAnnotation(Class<?> type, AnnotatedElement source) {
mergeCodec(source);
- if (source.isAnnotationPresent(JsonRawValue.class) && rawValueSource == null) {
+ if (annotations.has(source, JsonRawValue.class) && rawValueSource == null) {
rawValueSource = source;
}
mergeUnwrapped(source);
- JsonProperty property = source.getAnnotation(JsonProperty.class);
+ JsonProperty property = annotations.get(source, JsonProperty.class);
if (property == null) {
return;
}
@@ -2478,7 +2542,7 @@ final class ObjectCodecBuilder {
private void mergeCreatorParameter(Class<?> type, Parameter parameter) {
mergeCodec(parameter);
mergeUnwrapped(parameter);
- JsonProperty property = parameter.getAnnotation(JsonProperty.class);
+ JsonProperty property = annotations.get(parameter, JsonProperty.class);
if (unwrappedAnnotation == null) {
mergeAnnotation(type, parameter);
return;
@@ -2514,7 +2578,7 @@ final class ObjectCodecBuilder {
}
private void mergeUnwrapped(AnnotatedElement source) {
- JsonUnwrapped declared = source.getAnnotation(JsonUnwrapped.class);
+ JsonUnwrapped declared = annotations.get(source, JsonUnwrapped.class);
if (declared == null) {
return;
}
@@ -2536,8 +2600,8 @@ final class ObjectCodecBuilder {
}
private void mergeCodec(AnnotatedElement source) {
- JsonCodec declared = source.getAnnotation(JsonCodec.class);
- if (source.isAnnotationPresent(JsonBase64.class)) {
+ JsonCodec declared = annotations.get(source, JsonCodec.class);
+ if (annotations.has(source, JsonBase64.class)) {
if (declared != null || codecAnnotation != null) {
throw new ForyJsonException(
"@JsonBase64 cannot coexist with @JsonCodec for property " + name);
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorDeclaration.java b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorDeclaration.java
index c447a75f6..164bcf062 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorDeclaration.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorDeclaration.java
@@ -26,6 +26,7 @@ import java.lang.reflect.Modifier;
import org.apache.fory.annotation.Internal;
import org.apache.fory.json.ForyJsonException;
import org.apache.fory.json.annotation.JsonCreator;
+import org.apache.fory.json.resolver.JsonSharedRegistry;
/** Immutable result of selecting and validating one declared {@link JsonCreator}. */
@Internal
@@ -46,11 +47,11 @@ public final class JsonCreatorDeclaration {
return annotation;
}
- public static JsonCreatorDeclaration find(Class<?> type) {
+ public static JsonCreatorDeclaration find(Class<?> type, JsonSharedRegistry registry) {
Executable creator = null;
JsonCreator annotation = null;
for (Constructor<?> constructor : type.getDeclaredConstructors()) {
- JsonCreator candidate = constructor.getAnnotation(JsonCreator.class);
+ JsonCreator candidate = registry.annotation(type, constructor, JsonCreator.class);
if (candidate != null) {
validate(type, constructor);
if (creator != null) {
@@ -61,7 +62,7 @@ public final class JsonCreatorDeclaration {
}
}
for (Method method : type.getDeclaredMethods()) {
- JsonCreator candidate = method.getAnnotation(JsonCreator.class);
+ JsonCreator candidate = registry.annotation(type, method, JsonCreator.class);
if (candidate != null) {
validate(type, method);
if (creator != null) {
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/GeneratedJsonCodecFactories.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/GeneratedJsonCodecFactories.java
index 5720ca7d1..f5d479d9f 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/GeneratedJsonCodecFactories.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/GeneratedJsonCodecFactories.java
@@ -20,7 +20,7 @@
package org.apache.fory.json.resolver;
import java.util.Collections;
-import java.util.IdentityHashMap;
+import java.util.HashMap;
import java.util.Map;
import org.apache.fory.annotation.Internal;
import org.apache.fory.json.ForyJsonException;
@@ -29,23 +29,26 @@ import org.apache.fory.json.codec.GeneratedJsonCodecFactory;
/** Frozen GraalVM runtime reconstruction table for generated JSON companions. */
@Internal
public final class GeneratedJsonCodecFactories {
- private static Map<Class<?>, GeneratedJsonCodecFactory> factories = new IdentityHashMap<>();
+ private static Map<Key, GeneratedJsonCodecFactory> factories = new HashMap<>();
private static boolean frozen;
private GeneratedJsonCodecFactories() {}
- /** Publishes one hosted-analysis factory. */
- public static synchronized void register(Class<?> type, GeneratedJsonCodecFactory factory) {
+ /** Publishes one hosted-analysis factory for an exact target and optional Mixin pair. */
+ public static synchronized void register(
+ Class<?> type, Class<?> mixinType, GeneratedJsonCodecFactory factory) {
if (frozen) {
throw new ForyJsonException("Generated JSON codec factory table is already frozen");
}
- GeneratedJsonCodecFactory previous = factories.get(type);
+ Key key = new Key(type, mixinType);
+ GeneratedJsonCodecFactory previous = factories.get(key);
if (previous == null) {
- factories.put(type, factory);
+ factories.put(key, factory);
} else if (previous.getClass() != factory.getClass()) {
throw new ForyJsonException(
"Conflicting generated JSON codec factories for "
+ type.getName()
+ + (mixinType == null ? "" : " and " + mixinType.getName())
+ ": "
+ previous.getClass().getName()
+ " and "
@@ -56,13 +59,40 @@ public final class GeneratedJsonCodecFactories {
/** Freezes the hosted table into the native image heap. */
public static synchronized void freeze() {
if (!frozen) {
- factories = Collections.unmodifiableMap(new IdentityHashMap<>(factories));
+ factories = Collections.unmodifiableMap(new HashMap<>(factories));
frozen = true;
}
}
- /** Returns the exact runtime factory, or {@code null} when no companion was generated. */
- public static synchronized GeneratedJsonCodecFactory get(Class<?> type) {
- return factories.get(type);
+ /** Returns the exact pair factory, or {@code null} when no companion was generated. */
+ public static synchronized GeneratedJsonCodecFactory get(Class<?> type, Class<?> mixinType) {
+ return factories.get(new Key(type, mixinType));
+ }
+
+ private static final class Key {
+ private final Class<?> type;
+ private final Class<?> mixinType;
+
+ private Key(Class<?> type, Class<?> mixinType) {
+ this.type = type;
+ this.mixinType = mixinType;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (other == null || getClass() != other.getClass()) {
+ return false;
+ }
+ Key that = (Key) other;
+ return type == that.type && mixinType == that.mixinType;
+ }
+
+ @Override
+ public int hashCode() {
+ return 31 * System.identityHashCode(type) + System.identityHashCode(mixinType);
+ }
}
}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonMixinAnnotations.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonMixinAnnotations.java
new file mode 100644
index 000000000..74b19be92
--- /dev/null
+++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonMixinAnnotations.java
@@ -0,0 +1,502 @@
+/*
+ * 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.annotation.Annotation;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Target;
+import java.lang.reflect.AnnotatedElement;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Executable;
+import java.lang.reflect.Field;
+import java.lang.reflect.Member;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Parameter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.IdentityHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.fory.json.ForyJsonException;
+import org.apache.fory.json.JsonConfig;
+import org.apache.fory.json.annotation.JsonAnyGetter;
+import org.apache.fory.json.annotation.JsonAnyProperty;
+import org.apache.fory.json.annotation.JsonAnySetter;
+import org.apache.fory.json.annotation.JsonBase64;
+import org.apache.fory.json.annotation.JsonCodec;
+import org.apache.fory.json.annotation.JsonCreator;
+import org.apache.fory.json.annotation.JsonIgnore;
+import org.apache.fory.json.annotation.JsonMixin;
+import org.apache.fory.json.annotation.JsonMixinRemove;
+import org.apache.fory.json.annotation.JsonProperty;
+import org.apache.fory.json.annotation.JsonPropertyOrder;
+import org.apache.fory.json.annotation.JsonRawValue;
+import org.apache.fory.json.annotation.JsonSubTypes;
+import org.apache.fory.json.annotation.JsonType;
+import org.apache.fory.json.annotation.JsonUnwrapped;
+import org.apache.fory.json.annotation.JsonValue;
+
+/** Resolves immutable annotation overlays for the exact Mixins enabled by one runtime. */
+final class JsonMixinAnnotations {
+ @SuppressWarnings("unchecked")
+ private static final Class<? extends Annotation>[] SUPPORTED =
+ new Class[] {
+ JsonAnyGetter.class,
+ JsonAnyProperty.class,
+ JsonAnySetter.class,
+ JsonBase64.class,
+ JsonCodec.class,
+ JsonCreator.class,
+ JsonIgnore.class,
+ JsonProperty.class,
+ JsonPropertyOrder.class,
+ JsonRawValue.class,
+ JsonSubTypes.class,
+ JsonUnwrapped.class,
+ JsonValue.class
+ };
+
+ private static final Set<Class<? extends Annotation>> SUPPORTED_SET =
+ Collections.unmodifiableSet(new HashSet<>(Arrays.asList(SUPPORTED)));
+
+ private final IdentityHashMap<Class<?>, TargetOverlay> overlays;
+
+ JsonMixinAnnotations(JsonConfig config) {
+ IdentityHashMap<Class<?>, TargetOverlay> resolved = new IdentityHashMap<>();
+ for (Map.Entry<Class<?>, Class<?>> entry : config.mixins().entrySet()) {
+ Class<?> targetType = entry.getKey();
+ Class<?> mixinType = entry.getValue();
+ TargetOverlay overlay = resolve(targetType, mixinType);
+ if (!overlay.isEmpty()) {
+ resolved.put(targetType, overlay);
+ }
+ }
+ overlays = resolved;
+ }
+
+ TargetOverlay overlay(Class<?> targetType) {
+ return overlays.get(targetType);
+ }
+
+ static TargetOverlay resolve(Class<?> targetType, Class<?> mixinType) {
+ validateAssociation(targetType, mixinType);
+ Map<AnnotatedElement, ElementOverlay> declarations = new HashMap<>();
+ addOverlay(declarations, targetType, elementOverlay(mixinType, ElementType.TYPE));
+
+ for (Field sourceField : mixinType.getDeclaredFields()) {
+ if (sourceField.isSynthetic()) {
+ continue;
+ }
+ ElementOverlay sourceOverlay = elementOverlay(sourceField, ElementType.FIELD);
+ if (sourceOverlay == null) {
+ continue;
+ }
+ if (Modifier.isStatic(sourceField.getModifiers())) {
+ throw invalidSelector(targetType, mixinType, sourceField, "must be an instance field");
+ }
+ Field targetField = matchField(targetType, mixinType, sourceField);
+ addOverlay(declarations, targetField, sourceOverlay);
+ }
+
+ for (Method sourceMethod : mixinType.getDeclaredMethods()) {
+ if (sourceMethod.isSynthetic() || sourceMethod.isBridge()) {
+ continue;
+ }
+ ElementOverlay sourceOverlay = elementOverlay(sourceMethod, ElementType.METHOD);
+ ElementOverlay[] parameterOverlays = parameterOverlays(sourceMethod);
+ if (sourceOverlay == null && parameterOverlays == null) {
+ continue;
+ }
+ if (!Modifier.isAbstract(sourceMethod.getModifiers())) {
+ throw invalidSelector(targetType, mixinType, sourceMethod, "must be abstract");
+ }
+ Method targetMethod = matchMethod(targetType, mixinType, sourceMethod);
+ if (sourceOverlay != null
+ && sourceOverlay.mentions(JsonCreator.class)
+ && targetMethod.getDeclaringClass() != targetType) {
+ throw invalidSelector(
+ targetType, mixinType, sourceMethod, "cannot select an inherited @JsonCreator factory");
+ }
+ addOverlay(declarations, targetMethod, sourceOverlay);
+ addParameterOverlays(declarations, parameterOverlays, targetMethod);
+ }
+
+ for (Constructor<?> sourceConstructor : mixinType.getDeclaredConstructors()) {
+ ElementOverlay sourceOverlay = elementOverlay(sourceConstructor, ElementType.CONSTRUCTOR);
+ ElementOverlay[] parameterOverlays = parameterOverlays(sourceConstructor);
+ if (sourceOverlay == null && parameterOverlays == null) {
+ continue;
+ }
+ Constructor<?> targetConstructor = matchConstructor(targetType, mixinType, sourceConstructor);
+ addOverlay(declarations, targetConstructor, sourceOverlay);
+ addParameterOverlays(declarations, parameterOverlays, targetConstructor);
+ }
+ return new TargetOverlay(targetType, mixinType, declarations);
+ }
+
+ private static void validateAssociation(Class<?> targetType, Class<?> mixinType) {
+ JsonMixin declaration;
+ try {
+ declaration = mixinType.getDeclaredAnnotation(JsonMixin.class);
+ } catch (RuntimeException | LinkageError e) {
+ throw new ForyJsonException("Cannot read @JsonMixin on " + mixinType.getName(), e);
+ }
+ if (declaration == null || declaration.target() != targetType) {
+ throw new ForyJsonException(
+ "Invalid JSON Mixin association " + mixinType.getName() + " -> " + targetType.getName());
+ }
+ int sourceModifiers = mixinType.getModifiers();
+ if (mixinType.isAnnotation()
+ || mixinType.isEnum()
+ || mixinType.isAnonymousClass()
+ || mixinType.isLocalClass()
+ || mixinType.isMemberClass() && !Modifier.isStatic(sourceModifiers)
+ || (!mixinType.isInterface() && !Modifier.isAbstract(sourceModifiers))) {
+ throw new ForyJsonException(
+ "JSON Mixin source must be a named interface or static abstract class: "
+ + mixinType.getName());
+ }
+ if (mixinType.getInterfaces().length != 0
+ || (!mixinType.isInterface() && mixinType.getSuperclass() != Object.class)) {
+ throw new ForyJsonException(
+ "JSON Mixin source must not extend or implement another type: " + mixinType.getName());
+ }
+ if (targetType == mixinType
+ || targetType.isPrimitive()
+ || targetType.isArray()
+ || targetType.isAnnotation()) {
+ throw new ForyJsonException(
+ "Invalid JSON Mixin target " + targetType.getTypeName() + " for " + mixinType.getName());
+ }
+ }
+
+ private static void addParameterOverlays(
+ Map<AnnotatedElement, ElementOverlay> declarations,
+ ElementOverlay[] overlays,
+ Executable target) {
+ if (overlays == null) {
+ return;
+ }
+ Parameter[] targetParameters = target.getParameters();
+ for (int i = 0; i < overlays.length; i++) {
+ if (overlays[i] != null) {
+ addOverlay(declarations, targetParameters[i], overlays[i]);
+ }
+ }
+ }
+
+ private static ElementOverlay[] parameterOverlays(Executable executable) {
+ Parameter[] parameters = executable.getParameters();
+ ElementOverlay[] overlays = null;
+ for (int i = 0; i < parameters.length; i++) {
+ ElementOverlay overlay = elementOverlay(parameters[i], ElementType.PARAMETER);
+ if (overlay != null) {
+ if (overlays == null) {
+ overlays = new ElementOverlay[parameters.length];
+ }
+ overlays[i] = overlay;
+ }
+ }
+ return overlays;
+ }
+
+ private static void addOverlay(
+ Map<AnnotatedElement, ElementOverlay> declarations,
+ AnnotatedElement target,
+ ElementOverlay overlay) {
+ if (overlay == null) {
+ return;
+ }
+ ElementOverlay previous = declarations.put(target, overlay);
+ if (previous != null) {
+ throw new ForyJsonException("Duplicate JSON Mixin selector for " + target);
+ }
+ }
+
+ private static ElementOverlay elementOverlay(AnnotatedElement source, ElementType elementType) {
+ Map<Class<? extends Annotation>, Annotation> replacements = new HashMap<>();
+ for (Class<? extends Annotation> annotationType : SUPPORTED) {
+ Annotation annotation = declaredAnnotation(source, annotationType);
+ if (annotation != null) {
+ replacements.put(annotationType, annotation);
+ }
+ }
+ if (declaredAnnotation(source, JsonType.class) != null) {
+ throw new ForyJsonException("@JsonType cannot be declared by a JSON Mixin: " + source);
+ }
+ Set<Class<? extends Annotation>> removals = new HashSet<>();
+ JsonMixinRemove remove = declaredAnnotation(source, JsonMixinRemove.class);
+ if (remove != null) {
+ Class<? extends Annotation>[] removedTypes;
+ try {
+ removedTypes = remove.value();
+ } catch (RuntimeException | LinkageError e) {
+ throw new ForyJsonException("Cannot resolve @JsonMixinRemove on " + source, e);
+ }
+ if (removedTypes.length == 0) {
+ throw new ForyJsonException(
+ "@JsonMixinRemove must name at least one annotation on " + source);
+ }
+ for (Class<? extends Annotation> removedType : removedTypes) {
+ if (!SUPPORTED_SET.contains(removedType)) {
+ throw new ForyJsonException(
+ "Unsupported JSON Mixin removal " + removedType.getName() + " on " + source);
+ }
+ if (!supportsElement(removedType, elementType)) {
+ throw new ForyJsonException(
+ "JSON Mixin cannot remove @"
+ + removedType.getSimpleName()
+ + " from "
+ + elementType
+ + ' '
+ + source);
+ }
+ if (!removals.add(removedType)) {
+ throw new ForyJsonException(
+ "Duplicate JSON Mixin removal " + removedType.getName() + " on " + source);
+ }
+ if (replacements.containsKey(removedType)) {
+ throw new ForyJsonException(
+ "JSON Mixin both declares and removes " + removedType.getName() + " on " + source);
+ }
+ }
+ }
+ if (replacements.isEmpty() && removals.isEmpty()) {
+ return null;
+ }
+ return new ElementOverlay(source, replacements, removals);
+ }
+
+ private static boolean supportsElement(
+ Class<? extends Annotation> annotationType, ElementType elementType) {
+ Target target = annotationType.getDeclaredAnnotation(Target.class);
+ if (target == null) {
+ return true;
+ }
+ for (ElementType supported : target.value()) {
+ if (supported == elementType) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static Field matchField(Class<?> targetType, Class<?> mixinType, Field source) {
+ List<Field> matches = new ArrayList<>();
+ for (Class<?> current = targetType;
+ current != null && current != Object.class;
+ current = current.getSuperclass()) {
+ for (Field field : current.getDeclaredFields()) {
+ if (!field.isSynthetic()
+ && !Modifier.isStatic(field.getModifiers())
+ && field.getName().equals(source.getName())
+ && field.getType() == source.getType()) {
+ matches.add(field);
+ }
+ }
+ }
+ return oneMatch(targetType, mixinType, source, matches);
+ }
+
+ private static Method matchMethod(Class<?> targetType, Class<?> mixinType, Method source) {
+ Set<Method> candidates = new LinkedHashSet<>(Arrays.asList(targetType.getMethods()));
+ for (Class<?> current = targetType;
+ current != null && current != Object.class;
+ current = current.getSuperclass()) {
+ for (Method method : current.getDeclaredMethods()) {
+ if (!Modifier.isPublic(method.getModifiers())) {
+ candidates.add(method);
+ }
+ }
+ }
+ List<Method> matches = new ArrayList<>();
+ for (Method method : candidates) {
+ if (!method.isSynthetic()
+ && !method.isBridge()
+ && method.getName().equals(source.getName())
+ && method.getReturnType() == source.getReturnType()
+ && Arrays.equals(method.getParameterTypes(), source.getParameterTypes())) {
+ matches.add(method);
+ }
+ }
+ return oneMatch(targetType, mixinType, source, matches);
+ }
+
+ private static Constructor<?> matchConstructor(
+ Class<?> targetType, Class<?> mixinType, Constructor<?> source) {
+ List<Constructor<?>> matches = new ArrayList<>();
+ Class<?>[] sourceParameters = source.getParameterTypes();
+ for (Constructor<?> constructor : targetType.getDeclaredConstructors()) {
+ if (!constructor.isSynthetic()
+ && Arrays.equals(sourceParameters, constructor.getParameterTypes())) {
+ matches.add(constructor);
+ }
+ }
+ return oneMatch(targetType, mixinType, source, matches);
+ }
+
+ private static <T extends AnnotatedElement> T oneMatch(
+ Class<?> targetType, Class<?> mixinType, AnnotatedElement source, List<T> matches) {
+ if (matches.size() != 1) {
+ throw invalidSelector(
+ targetType,
+ mixinType,
+ source,
+ matches.isEmpty() ? "does not match a target declaration" : "is ambiguous");
+ }
+ return matches.get(0);
+ }
+
+ private static ForyJsonException invalidSelector(
+ Class<?> targetType, Class<?> mixinType, AnnotatedElement source, String reason) {
+ return new ForyJsonException(
+ "Invalid JSON Mixin selector "
+ + source
+ + " from "
+ + mixinType.getName()
+ + " for "
+ + targetType.getName()
+ + ": "
+ + reason);
+ }
+
+ private static <A extends Annotation> A declaredAnnotation(
+ AnnotatedElement element, Class<A> annotationType) {
+ try {
+ return element.getDeclaredAnnotation(annotationType);
+ } catch (RuntimeException | LinkageError e) {
+ throw new ForyJsonException(
+ "Cannot read @" + annotationType.getSimpleName() + " on " + element, e);
+ }
+ }
+
+ static <A extends Annotation> A targetAnnotation(
+ AnnotatedElement element, Class<A> annotationType) {
+ validateTargetControl(element);
+ return declaredAnnotation(element, annotationType);
+ }
+
+ static void validateTargetControl(AnnotatedElement element) {
+ if (declaredAnnotation(element, JsonMixinRemove.class) != null
+ && declaredAnnotation(declarationOwner(element), JsonMixin.class) == null) {
+ throw new ForyJsonException(
+ "@JsonMixinRemove is valid only inside a direct @JsonMixin source: " + element);
+ }
+ }
+
+ private static Class<?> declarationOwner(AnnotatedElement element) {
+ if (element instanceof Class<?>) {
+ return (Class<?>) element;
+ }
+ if (element instanceof Member) {
+ return ((Member) element).getDeclaringClass();
+ }
+ if (element instanceof Parameter) {
+ return ((Parameter) element).getDeclaringExecutable().getDeclaringClass();
+ }
+ throw new ForyJsonException("Unsupported JSON annotation declaration " + element);
+ }
+
+ static final class TargetOverlay {
+ private final Class<?> targetType;
+ private final Class<?> mixinType;
+ private final Map<AnnotatedElement, ElementOverlay> declarations;
+
+ private TargetOverlay(
+ Class<?> targetType,
+ Class<?> mixinType,
+ Map<AnnotatedElement, ElementOverlay> declarations) {
+ this.targetType = targetType;
+ this.mixinType = mixinType;
+ this.declarations = Collections.unmodifiableMap(new HashMap<>(declarations));
+ }
+
+ Class<?> mixinType() {
+ return mixinType;
+ }
+
+ boolean isEmpty() {
+ return declarations.isEmpty();
+ }
+
+ Set<AnnotatedElement> sourceDeclarations() {
+ Set<AnnotatedElement> sources = new HashSet<>();
+ for (ElementOverlay declaration : declarations.values()) {
+ sources.add(declaration.source);
+ }
+ return Collections.unmodifiableSet(sources);
+ }
+
+ Set<AnnotatedElement> targetDeclarations() {
+ return declarations.keySet();
+ }
+
+ <A extends Annotation> A annotation(AnnotatedElement target, Class<A> annotationType) {
+ validateTargetControl(target);
+ ElementOverlay overlay = declarations.get(target);
+ if (overlay != null) {
+ Annotation replacement = overlay.replacements.get(annotationType);
+ if (replacement != null) {
+ return annotationType.cast(replacement);
+ }
+ if (overlay.removals.contains(annotationType)) {
+ return null;
+ }
+ }
+ if (target instanceof Class<?>
+ && target != targetType
+ && (annotationType == JsonCodec.class || annotationType == JsonPropertyOrder.class)
+ && removed(targetType, annotationType)) {
+ return null;
+ }
+ return declaredAnnotation(target, annotationType);
+ }
+
+ boolean removed(AnnotatedElement target, Class<? extends Annotation> annotationType) {
+ ElementOverlay overlay = declarations.get(target);
+ return overlay != null && overlay.removals.contains(annotationType);
+ }
+ }
+
+ private static final class ElementOverlay {
+ private final AnnotatedElement source;
+ private final Map<Class<? extends Annotation>, Annotation> replacements;
+ private final Set<Class<? extends Annotation>> removals;
+
+ private ElementOverlay(
+ AnnotatedElement source,
+ Map<Class<? extends Annotation>, Annotation> replacements,
+ Set<Class<? extends Annotation>> removals) {
+ this.source = source;
+ this.replacements = Collections.unmodifiableMap(new HashMap<>(replacements));
+ this.removals = Collections.unmodifiableSet(new HashSet<>(removals));
+ }
+
+ private boolean mentions(Class<? extends Annotation> annotationType) {
+ return replacements.containsKey(annotationType) || removals.contains(annotationType);
+ }
+ }
+}
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 52d0e6025..cf359827b 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
@@ -20,7 +20,9 @@
package org.apache.fory.json.resolver;
import java.io.File;
+import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;
+import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Field;
@@ -172,6 +174,7 @@ public final class JsonSharedRegistry {
private final PropertyNamingStrategy propertyNamingStrategy;
private final boolean writeNullFields;
private final ClassLoader classLoader;
+ private final JsonMixinAnnotations mixinAnnotations;
private final IdentityHashMap<Class<?>, JsonSubTypesInfo> subTypesCache;
private final IdentityHashMap<Class<?>, JsonCodecDeclaration> codecDeclarations;
private final Set<Class<?>> typesWithoutCodecDeclaration;
@@ -198,6 +201,7 @@ public final class JsonSharedRegistry {
propertyNamingStrategy = config.propertyNamingStrategy();
writeNullFields = config.writeNullFields();
classLoader = config.classLoader();
+ mixinAnnotations = new JsonMixinAnnotations(config);
exactCodecs = new IdentityHashMap<>();
subTypesCache = new IdentityHashMap<>();
codecDeclarations = new IdentityHashMap<>();
@@ -255,22 +259,26 @@ public final class JsonSharedRegistry {
}
GeneratedJsonCodec<?> generatedCodec(Class<?> type) {
- if (type.getDeclaredAnnotation(JsonType.class) == null) {
+ Class<?> mixinType = mixinType(type);
+ boolean directGenerated = type.getDeclaredAnnotation(JsonType.class) != null;
+ if (!directGenerated && mixinType == null) {
return null;
}
- GeneratedJsonCodec<?> codec = generatedCodecIfPresent(type);
- if (codec == null) {
- throw new ForyJsonException(
- "Missing generated JSON codec "
- + generatedCodecBinaryName(type)
- + " for @JsonType object model "
- + type.getName()
- + "; enable the Fory annotation processor and preserve its generated R8 rules");
+ try {
+ GeneratedJsonCodec<?> codec = generatedCodecIfPresent(type, mixinType);
+ if (codec == null
+ && (directGenerated
+ || mixinType != null
+ && (AndroidSupport.IS_ANDROID || GraalvmSupport.IN_GRAALVM_NATIVE_IMAGE))) {
+ throw missingGeneratedCodec(type, mixinType, "JSON object model");
+ }
+ return codec;
+ } catch (ForyJsonException e) {
+ throw mixinSchemaFailure(type, e);
}
- return codec;
}
- private GeneratedJsonCodec<?> generatedCodecIfPresent(Class<?> type) {
+ private GeneratedJsonCodec<?> generatedCodecIfPresent(Class<?> type, Class<?> mixinType) {
GeneratedJsonCodec<?> codec = generatedCodecs.get(type);
if (codec != null) {
return codec;
@@ -279,7 +287,7 @@ public final class JsonSharedRegistry {
synchronized (generatedCodecs) {
codec = generatedCodecs.get(type);
if (codec == null && !typesWithoutGeneratedCodec.contains(type)) {
- codec = loadGeneratedCodec(type);
+ codec = loadGeneratedCodec(type, mixinType);
if (codec == null) {
typesWithoutGeneratedCodec.add(type);
} else {
@@ -291,15 +299,38 @@ public final class JsonSharedRegistry {
return codec;
}
- private GeneratedJsonCodec<?> loadGeneratedCodec(Class<?> type) {
+ private static ForyJsonException missingGeneratedCodec(
+ Class<?> type, Class<?> mixinType, String representation) {
+ String name =
+ mixinType == null
+ ? generatedCodecBinaryName(type)
+ : generatedMixinCodecBinaryName(mixinType, type);
+ return new ForyJsonException(
+ "Missing generated JSON codec "
+ + name
+ + " for "
+ + representation
+ + " "
+ + type.getName()
+ + "; enable the Fory annotation processor and preserve its generated R8 rules");
+ }
+
+ private GeneratedJsonCodec<?> loadGeneratedCodec(Class<?> type, Class<?> mixinType) {
if (GraalvmSupport.isGraalRuntime()) {
- GeneratedJsonCodecFactory factory = GeneratedJsonCodecFactories.get(type);
+ GeneratedJsonCodecFactory factory = GeneratedJsonCodecFactories.get(type, mixinType);
return factory == null ? null : validateGeneratedCodec(type, factory.create());
}
- String generatedName = generatedCodecBinaryName(type);
+ String generatedName =
+ mixinType == null
+ ? generatedCodecBinaryName(type)
+ : generatedMixinCodecBinaryName(mixinType, type);
Class<?> generatedClass;
try {
- generatedClass = Class.forName(generatedName, false, type.getClassLoader());
+ generatedClass =
+ Class.forName(
+ generatedName,
+ false,
+ mixinType == null ? type.getClassLoader() : mixinType.getClassLoader());
} catch (ClassNotFoundException e) {
return null;
} catch (LinkageError e) {
@@ -593,9 +624,23 @@ public final class JsonSharedRegistry {
return GeneratedClassNames.withSuffix(binaryName, "_ForyJsonCodec");
}
+ /** Returns the deterministic generated companion name for one target-Mixin pair. */
+ @Internal
+ public static String generatedMixinCodecBinaryName(Class<?> mixinType, Class<?> targetType) {
+ String sourceName = mixinType.getName();
+ int packageEnd = sourceName.lastIndexOf('.');
+ String sourcePackage = packageEnd < 0 ? "" : sourceName.substring(0, packageEnd + 1);
+ String sourceSimple = packageEnd < 0 ? sourceName : sourceName.substring(packageEnd + 1);
+ return sourcePackage
+ + GeneratedClassNames.escapeBinarySimpleName(sourceSimple)
+ + "_ForyJsonMixin_"
+ + GeneratedClassNames.escapeBinarySimpleName(targetType.getName())
+ + "_ForyJsonCodec";
+ }
+
public JsonValueCodec<?> createCodec(
Class<?> rawType, TypeRef<?> typeRef, JsonTypeResolver localResolver) {
- JsonValueCodec<?> customCodec = customCodecs.get(rawType);
+ JsonValueCodec<?> customCodec = customCodec(rawType);
if (customCodec != null) {
return customCodec;
}
@@ -734,6 +779,71 @@ public final class JsonSharedRegistry {
return classLoader;
}
+ /** Returns the effective annotation for one declaration in an exact target context. */
+ @Internal
+ public <A extends Annotation> A annotation(
+ Class<?> targetType, AnnotatedElement declaration, Class<A> annotationType) {
+ JsonMixinAnnotations.TargetOverlay overlay = mixinAnnotations.overlay(targetType);
+ return overlay == null
+ ? JsonMixinAnnotations.targetAnnotation(declaration, annotationType)
+ : overlay.annotation(declaration, annotationType);
+ }
+
+ Class<?> mixinType(Class<?> targetType) {
+ JsonMixinAnnotations.TargetOverlay overlay = mixinAnnotations.overlay(targetType);
+ return overlay == null ? null : overlay.mixinType();
+ }
+
+ /** Adds exact pair context to a cold effective-schema validation failure. */
+ @Internal
+ public ForyJsonException mixinSchemaFailure(Class<?> targetType, ForyJsonException failure) {
+ Class<?> mixinType = mixinType(targetType);
+ if (mixinType == null) {
+ return failure;
+ }
+ return new ForyJsonException(
+ "Invalid effective JSON Mixin schema for target "
+ + targetType.getName()
+ + " from source "
+ + mixinType.getName()
+ + ": "
+ + failure.getMessage(),
+ failure);
+ }
+
+ /** Resolves one target-Mixin overlay for hosted metadata discovery. */
+ @Internal
+ public static JsonMixinView resolveMixin(Class<?> targetType, Class<?> mixinType) {
+ return new JsonMixinView(JsonMixinAnnotations.resolve(targetType, mixinType));
+ }
+
+ /** Read-only hosted view of one fully validated structural Mixin overlay. */
+ @Internal
+ public static final class JsonMixinView {
+ private final JsonMixinAnnotations.TargetOverlay overlay;
+
+ private JsonMixinView(JsonMixinAnnotations.TargetOverlay overlay) {
+ this.overlay = overlay;
+ }
+
+ public boolean isEmpty() {
+ return overlay.isEmpty();
+ }
+
+ public Set<AnnotatedElement> sourceDeclarations() {
+ return overlay.sourceDeclarations();
+ }
+
+ public Set<AnnotatedElement> targetDeclarations() {
+ return overlay.targetDeclarations();
+ }
+
+ public <A extends Annotation> A annotation(
+ AnnotatedElement declaration, Class<A> annotationType) {
+ return overlay.annotation(declaration, annotationType);
+ }
+ }
+
JsonValueCodec<?> customCodec(Class<?> type) {
return customCodecs.get(type);
}
@@ -742,21 +852,25 @@ public final class JsonSharedRegistry {
if (targetType.isAnnotation()) {
return null;
}
- synchronized (codecDeclarations) {
- JsonCodecDeclaration cached = codecDeclarations.get(targetType);
- if (cached != null) {
- return cached;
- }
- if (typesWithoutCodecDeclaration.contains(targetType)) {
- return null;
- }
- JsonCodecDeclaration resolved = resolveCodecDeclaration(targetType);
- if (resolved == null) {
- typesWithoutCodecDeclaration.add(targetType);
- } else {
- codecDeclarations.put(targetType, resolved);
+ try {
+ synchronized (codecDeclarations) {
+ JsonCodecDeclaration cached = codecDeclarations.get(targetType);
+ if (cached != null) {
+ return cached;
+ }
+ if (typesWithoutCodecDeclaration.contains(targetType)) {
+ return null;
+ }
+ JsonCodecDeclaration resolved = resolveCodecDeclaration(targetType);
+ if (resolved == null) {
+ typesWithoutCodecDeclaration.add(targetType);
+ } else {
+ codecDeclarations.put(targetType, resolved);
+ }
+ return resolved;
}
- return resolved;
+ } catch (ForyJsonException e) {
+ throw mixinSchemaFailure(targetType, e);
}
}
@@ -764,25 +878,31 @@ public final class JsonSharedRegistry {
if (targetType.isAnnotation()) {
return null;
}
- synchronized (valueDeclarations) {
- JsonValueDeclaration cached = valueDeclarations.get(targetType);
- if (cached != null) {
- return cached;
- }
- if (typesWithoutValueDeclaration.contains(targetType)) {
- return null;
- }
- GeneratedJsonCodec<?> generatedCodec =
- targetType.getDeclaredAnnotation(JsonType.class) == null
- ? null
- : generatedCodecIfPresent(targetType);
- JsonValueDeclaration resolved = JsonValueDeclaration.resolve(targetType, generatedCodec);
- if (resolved == null) {
- typesWithoutValueDeclaration.add(targetType);
- } else {
- valueDeclarations.put(targetType, resolved);
+ try {
+ synchronized (valueDeclarations) {
+ JsonValueDeclaration cached = valueDeclarations.get(targetType);
+ if (cached != null) {
+ return cached;
+ }
+ if (typesWithoutValueDeclaration.contains(targetType)) {
+ return null;
+ }
+ Class<?> mixinType = mixinType(targetType);
+ boolean loadGeneratedCodec =
+ targetType.getDeclaredAnnotation(JsonType.class) != null || mixinType != null;
+ GeneratedJsonCodec<?> generatedCodec =
+ loadGeneratedCodec ? generatedCodecIfPresent(targetType, mixinType) : null;
+ JsonValueDeclaration resolved =
+ JsonValueDeclaration.resolve(targetType, generatedCodec, this);
+ if (resolved == null) {
+ typesWithoutValueDeclaration.add(targetType);
+ } else {
+ valueDeclarations.put(targetType, resolved);
+ }
+ return resolved;
}
- return resolved;
+ } catch (ForyJsonException e) {
+ throw mixinSchemaFailure(targetType, e);
}
}
@@ -798,7 +918,7 @@ public final class JsonSharedRegistry {
}
private JsonCodecDeclaration resolveCodecDeclaration(Class<?> targetType) {
- DeclarationCandidate direct = declaredCodec(targetType);
+ DeclarationCandidate direct = declaredCodec(targetType, targetType);
if (direct != null) {
return new JsonCodecDeclaration(direct.codecClass, new Class<?>[] {targetType}, false);
}
@@ -821,7 +941,7 @@ public final class JsonSharedRegistry {
return new JsonCodecDeclaration(codecClass, origins, true);
}
- private static List<DeclarationCandidate> inheritedCodecCandidates(Class<?> targetType) {
+ private List<DeclarationCandidate> inheritedCodecCandidates(Class<?> targetType) {
List<DeclarationCandidate> candidates = new ArrayList<>();
Set<Class<?>> visited = Collections.newSetFromMap(new IdentityHashMap<Class<?>, Boolean>());
Deque<Class<?>> pending = new ArrayDeque<>();
@@ -832,7 +952,7 @@ public final class JsonSharedRegistry {
continue;
}
if (!current.isAnnotation()) {
- DeclarationCandidate candidate = declaredCodec(current);
+ DeclarationCandidate candidate = declaredCodec(targetType, current);
if (candidate != null) {
candidates.add(candidate);
}
@@ -872,10 +992,12 @@ public final class JsonSharedRegistry {
return frontier;
}
- private static DeclarationCandidate declaredCodec(Class<?> declarationType) {
+ private DeclarationCandidate declaredCodec(Class<?> targetType, Class<?> declarationType) {
JsonCodec annotation;
try {
- annotation = declarationType.getDeclaredAnnotation(JsonCodec.class);
+ annotation = annotation(targetType, declarationType, JsonCodec.class);
+ } catch (ForyJsonException e) {
+ throw e;
} catch (RuntimeException | LinkageError e) {
throw new ForyJsonException(
"Cannot read @JsonCodec declared on " + declarationType.getName(), e);
@@ -1015,18 +1137,22 @@ public final class JsonSharedRegistry {
}
JsonSubTypesInfo subTypesInfo(Class<?> baseType) {
- JsonSubTypes annotation = baseType.getDeclaredAnnotation(JsonSubTypes.class);
- if (annotation == null) {
- return null;
- }
- synchronized (subTypesCache) {
- JsonSubTypesInfo cached = subTypesCache.get(baseType);
- if (cached != null) {
- return cached;
+ try {
+ JsonSubTypes annotation = annotation(baseType, baseType, JsonSubTypes.class);
+ if (annotation == null) {
+ return null;
+ }
+ synchronized (subTypesCache) {
+ JsonSubTypesInfo cached = subTypesCache.get(baseType);
+ if (cached != null) {
+ return cached;
+ }
+ JsonSubTypesInfo resolved = buildSubTypesInfo(baseType, annotation);
+ subTypesCache.put(baseType, resolved);
+ return resolved;
}
- JsonSubTypesInfo resolved = buildSubTypesInfo(baseType, annotation);
- subTypesCache.put(baseType, resolved);
- return resolved;
+ } catch (ForyJsonException e) {
+ throw mixinSchemaFailure(baseType, e);
}
}
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 3f66da527..d054f6561 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
@@ -1819,6 +1819,7 @@ public final class JsonTypeResolver {
sharedRegistry.propertyDiscoveryEnabled(),
sharedRegistry.propertyNamingStrategy(),
sharedRegistry.writeNullFields(),
+ sharedRegistry,
generatedCodec);
}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonValueDeclaration.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonValueDeclaration.java
index 8f8e994ca..85b67d2e6 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonValueDeclaration.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonValueDeclaration.java
@@ -61,11 +61,12 @@ final class JsonValueDeclaration {
return codec;
}
- static JsonValueDeclaration resolve(Class<?> type, GeneratedJsonCodec<?> generatedCodec) {
+ static JsonValueDeclaration resolve(
+ Class<?> type, GeneratedJsonCodec<?> generatedCodec, JsonSharedRegistry registry) {
List<Member> members = new ArrayList<>();
- collectFields(type, members);
- collectMethods(type, members);
- coalesceRecordMember(type, members, generatedCodec);
+ collectFields(type, members, registry);
+ collectMethods(type, members, registry);
+ coalesceRecordMember(type, members, generatedCodec, registry);
if (members.isEmpty()) {
return null;
}
@@ -78,16 +79,17 @@ final class JsonValueDeclaration {
boolean raw;
if (member instanceof Field) {
Field field = (Field) member;
- validateField(field);
+ validateField(type, field, registry);
accessor = generatedAccessor(generatedCodec, field);
- raw = field.isAnnotationPresent(JsonRawValue.class);
+ raw = registry.annotation(type, field, JsonRawValue.class) != null;
} else {
Method method = (Method) member;
- validateMethod(method);
+ validateMethod(type, method, registry);
accessor = generatedAccessor(generatedCodec, method);
- raw = method.isAnnotationPresent(JsonRawValue.class);
+ raw = registry.annotation(type, method, JsonRawValue.class) != null;
}
- Executable creator = valueCreator(type, generatedCodec);
+ JsonCreatorDeclaration creatorDeclaration = JsonCreatorDeclaration.find(type, registry);
+ Executable creator = valueCreator(type, generatedCodec, registry, creatorDeclaration);
GeneratedJsonCodec<?> creatorBackend =
generatedCodec != null && generatedCodec.matchesCreator(creator) ? generatedCodec : null;
return new JsonValueDeclaration(
@@ -106,23 +108,25 @@ final class JsonValueDeclaration {
: JsonFieldAccessor.forGetter((Method) member);
}
- private static void collectFields(Class<?> type, List<Member> members) {
+ private static void collectFields(
+ Class<?> type, List<Member> members, JsonSharedRegistry registry) {
for (Class<?> current = type;
current != null && current != Object.class;
current = current.getSuperclass()) {
for (Field field : current.getDeclaredFields()) {
- if (field.isAnnotationPresent(JsonValue.class)) {
- validateField(field);
+ if (registry.annotation(type, field, JsonValue.class) != null) {
+ validateField(type, field, registry);
members.add(field);
}
}
}
}
- private static void collectMethods(Class<?> type, List<Member> members) {
+ private static void collectMethods(
+ Class<?> type, List<Member> members, JsonSharedRegistry registry) {
for (Method method : type.getMethods()) {
- if (method.isAnnotationPresent(JsonValue.class)) {
- validateMethod(method);
+ if (registry.annotation(type, method, JsonValue.class) != null) {
+ validateMethod(type, method, registry);
members.add(method);
}
}
@@ -130,17 +134,20 @@ final class JsonValueDeclaration {
current != null && current != Object.class;
current = current.getSuperclass()) {
for (Method method : current.getDeclaredMethods()) {
- if (!method.isAnnotationPresent(JsonValue.class)
+ if (registry.annotation(type, method, JsonValue.class) == null
|| Modifier.isPublic(method.getModifiers())) {
continue;
}
- validateMethod(method);
+ validateMethod(type, method, registry);
}
}
}
private static void coalesceRecordMember(
- Class<?> type, List<Member> members, GeneratedJsonCodec<?> generatedCodec) {
+ Class<?> type,
+ List<Member> members,
+ GeneratedJsonCodec<?> generatedCodec,
+ JsonSharedRegistry registry) {
// Android desugaring removes the platform Record identity but preserves the propagated field
// and accessor annotations. The validated companion is therefore the authoritative Record
// identity and lets this semantic owner select the direct accessor without structural guesses.
@@ -163,8 +170,8 @@ final class JsonValueDeclaration {
&& field.getDeclaringClass() == type
&& method.getDeclaringClass() == type
&& field.getName().equals(method.getName())
- && field.isAnnotationPresent(JsonRawValue.class)
- == method.isAnnotationPresent(JsonRawValue.class)) {
+ && (registry.annotation(type, field, JsonRawValue.class) != null)
+ == (registry.annotation(type, method, JsonRawValue.class) != null)) {
members.clear();
members.add(
generatedCodec != null && generatedCodec.validatedAccessor(method) != null
@@ -173,7 +180,7 @@ final class JsonValueDeclaration {
}
}
- private static void validateField(Field field) {
+ private static void validateField(Class<?> type, Field field, JsonSharedRegistry registry) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers)
|| Modifier.isTransient(modifiers)
@@ -181,16 +188,16 @@ final class JsonValueDeclaration {
|| field.getType() != String.class) {
throw new ForyJsonException("Invalid @JsonValue field " + field);
}
- if (field.isAnnotationPresent(JsonCodec.class)
- || field.isAnnotationPresent(JsonBase64.class)
- || field.isAnnotationPresent(JsonAnyProperty.class)
- || field.isAnnotationPresent(JsonUnwrapped.class)
- || field.isAnnotationPresent(JsonIgnore.class)) {
+ if (registry.annotation(type, field, JsonCodec.class) != null
+ || registry.annotation(type, field, JsonBase64.class) != null
+ || registry.annotation(type, field, JsonAnyProperty.class) != null
+ || registry.annotation(type, field, JsonUnwrapped.class) != null
+ || registry.annotation(type, field, JsonIgnore.class) != null) {
throw new ForyJsonException("Conflicting JSON annotations on @JsonValue field " + field);
}
}
- private static void validateMethod(Method method) {
+ private static void validateMethod(Class<?> type, Method method, JsonSharedRegistry registry) {
int modifiers = method.getModifiers();
if (!Modifier.isPublic(modifiers)
|| Modifier.isStatic(modifiers)
@@ -202,17 +209,20 @@ final class JsonValueDeclaration {
|| method.getReturnType() != String.class) {
throw new ForyJsonException("Invalid @JsonValue method " + method);
}
- if (method.isAnnotationPresent(JsonCodec.class)
- || method.isAnnotationPresent(JsonBase64.class)
- || method.isAnnotationPresent(JsonAnyGetter.class)
- || method.isAnnotationPresent(JsonUnwrapped.class)
- || method.isAnnotationPresent(JsonIgnore.class)) {
+ if (registry.annotation(type, method, JsonCodec.class) != null
+ || registry.annotation(type, method, JsonBase64.class) != null
+ || registry.annotation(type, method, JsonAnyGetter.class) != null
+ || registry.annotation(type, method, JsonUnwrapped.class) != null
+ || registry.annotation(type, method, JsonIgnore.class) != null) {
throw new ForyJsonException("Conflicting JSON annotations on @JsonValue method " + method);
}
}
- private static Executable valueCreator(Class<?> type, GeneratedJsonCodec<?> generatedCodec) {
- JsonCreatorDeclaration declaration = JsonCreatorDeclaration.find(type);
+ private static Executable valueCreator(
+ Class<?> type,
+ GeneratedJsonCodec<?> generatedCodec,
+ JsonSharedRegistry registry,
+ JsonCreatorDeclaration declaration) {
if (declaration == null) {
return null;
}
@@ -224,7 +234,7 @@ final class JsonValueDeclaration {
return null;
}
Parameter parameter = executable.getParameters()[0];
- if (parameter.isAnnotationPresent(JsonProperty.class)) {
+ if (registry.annotation(type, parameter, JsonProperty.class) != null) {
rejectRecordCreator(type, generatedCodec);
return null;
}
diff --git a/java/fory-json/src/main/java17/org/apache/fory/json/codec/ForyJsonGraalVMFeature.java b/java/fory-json/src/main/java17/org/apache/fory/json/codec/ForyJsonGraalVMFeature.java
index c6e8194ab..1f99b4cba 100644
--- a/java/fory-json/src/main/java17/org/apache/fory/json/codec/ForyJsonGraalVMFeature.java
+++ b/java/fory-json/src/main/java17/org/apache/fory/json/codec/ForyJsonGraalVMFeature.java
@@ -21,6 +21,7 @@ package org.apache.fory.json.codec;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
+import java.lang.reflect.Executable;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
@@ -42,10 +43,14 @@ import org.apache.fory.json.ForyJson;
import org.apache.fory.json.annotation.JsonBase64;
import org.apache.fory.json.annotation.JsonCodec;
import org.apache.fory.json.annotation.JsonCreator;
+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.annotation.JsonUnwrapped;
+import org.apache.fory.json.annotation.JsonValue;
import org.apache.fory.json.resolver.GeneratedJsonCodecFactories;
import org.apache.fory.json.resolver.JsonSharedRegistry;
+import org.apache.fory.json.resolver.JsonSharedRegistry.JsonMixinView;
import org.apache.fory.platform.GraalvmSupport;
import org.apache.fory.reflect.ReflectionUtils;
import org.apache.fory.reflect.TypeRef;
@@ -63,6 +68,7 @@ final class ForyJsonGraalVMFeature implements Feature {
private final Set<Class<?>> processedReachableTypes = ConcurrentHashMap.newKeySet();
private final Set<Class<?>> processedDeclarations = ConcurrentHashMap.newKeySet();
private final Set<Class<?>> processedModels = ConcurrentHashMap.newKeySet();
+ private final Set<Class<?>> processedMixins = ConcurrentHashMap.newKeySet();
private final Set<Class<?>> processedCodecs = ConcurrentHashMap.newKeySet();
private final Set<Class<?>> processedContainers = ConcurrentHashMap.newKeySet();
@@ -74,6 +80,16 @@ final class ForyJsonGraalVMFeature implements Feature {
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
RuntimeClassInitialization.initializeAtBuildTime(GeneratedJsonCodecFactories.class);
+ // Exact target-Mixin keys are retained in the frozen factory table and therefore become image
+ // heap objects together with the table. Derive the private key name from its enclosing class so
+ // relocated/shaded packages remain valid.
+ RuntimeClassInitialization.initializeAtBuildTime(
+ GeneratedJsonCodecFactories.class.getName() + "$Key");
+ // Hosted Mixin discovery deliberately reuses the runtime's structural resolver so build-time
+ // reachability and runtime semantics cannot drift. Its static state contains only the immutable
+ // supported-annotation set and is therefore safe to initialize in the image builder.
+ RuntimeClassInitialization.initializeAtBuildTime(
+ ForyJson.class.getPackage().getName() + ".resolver.JsonMixinAnnotations");
access.registerSubtypeReachabilityHandler(this::processReachableType, Object.class);
}
@@ -94,6 +110,10 @@ final class ForyJsonGraalVMFeature implements Feature {
if (type.getDeclaredAnnotation(JsonType.class) != null) {
changed |= registerModel(access, type);
}
+ JsonMixin mixin = type.getDeclaredAnnotation(JsonMixin.class);
+ if (mixin != null) {
+ changed |= registerMixin(access, type, mixin.target());
+ }
if (type == ForyJson.class) {
registerBuiltInTypes(access);
changed = true;
@@ -120,13 +140,154 @@ final class ForyJsonGraalVMFeature implements Feature {
RuntimeReflection.registerForReflectiveInstantiation(type);
}
}
- registerGeneratedCodec(access, type);
+ registerGeneratedCodec(access, type, null);
registerSubtypes(access, type);
return true;
}
- private void registerGeneratedCodec(DuringAnalysisAccess access, Class<?> type) {
- String codecName = JsonSharedRegistry.generatedCodecBinaryName(type);
+ private boolean registerMixin(
+ DuringAnalysisAccess access, Class<?> mixinType, Class<?> targetType) {
+ if (!processedMixins.add(mixinType)) {
+ return false;
+ }
+ JsonMixinView annotations = JsonSharedRegistry.resolveMixin(targetType, mixinType);
+ RuntimeReflection.register(mixinType);
+ if (annotations.isEmpty()) {
+ return true;
+ }
+ registerReflectiveDeclarations(annotations.sourceDeclarations());
+ registerReflectiveDeclarations(annotations.targetDeclarations());
+ // Retain every directly declared hierarchy codec plus the exact Mixin replacement. Runtime
+ // resolution remains the sole owner of codec precedence and conflict validation.
+ registerDeclarations(targetType);
+ JsonCodec directTypeCodec = annotations.annotation(targetType, JsonCodec.class);
+ registerCodecs(directTypeCodec);
+ RuntimeReflection.register(targetType);
+ registerContainer(targetType);
+ boolean intrinsicTarget =
+ targetType.isEnum()
+ || Collection.class.isAssignableFrom(targetType)
+ || Map.class.isAssignableFrom(targetType);
+ boolean hasDirectTypeCodec = directTypeCodec != null;
+ boolean hasTypeCodec = hasDirectTypeCodec || hasInheritedTypeCodec(targetType, annotations);
+ boolean hasJsonValue =
+ (!hasTypeCodec || isCompleteTypeCodec(directTypeCodec))
+ && registerJsonValueDeclarations(access, targetType, annotations);
+ JsonSubTypes subTypes = annotation(annotations, targetType, JsonSubTypes.class);
+ // Annotation-selected complete representations make ordinary object metadata unreachable.
+ // Keep builder registrations and built-in codec policy runtime-owned by treating only the
+ // effective annotations visible here as hosted reachability facts.
+ if (!intrinsicTarget && !hasTypeCodec && !hasJsonValue && subTypes == null) {
+ registerModelHierarchy(access, targetType, annotations);
+ if (!targetType.isRecord()
+ && GraalvmSupport.needReflectionRegisterForCreation(targetType)) {
+ RuntimeReflection.registerForReflectiveInstantiation(targetType);
+ }
+ }
+ registerGeneratedCodec(access, targetType, mixinType);
+ if (!hasTypeCodec && !hasJsonValue) {
+ registerSubtypes(access, targetType, annotations);
+ }
+ return true;
+ }
+
+ private boolean hasInheritedTypeCodec(Class<?> type, JsonMixinView annotations) {
+ Class<?> superclass = type.getSuperclass();
+ if (superclass != null
+ && (annotation(annotations, superclass, JsonCodec.class) != null
+ || hasInheritedTypeCodec(superclass, annotations))) {
+ return true;
+ }
+ for (Class<?> interfaceType : type.getInterfaces()) {
+ if (annotation(annotations, interfaceType, JsonCodec.class) != null
+ || hasInheritedTypeCodec(interfaceType, annotations)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean isCompleteTypeCodec(JsonCodec annotation) {
+ return annotation != null
+ && annotation.value() != JsonCodec.NoJsonValueCodec.class
+ && annotation.elementCodec() == JsonCodec.NoJsonValueCodec.class
+ && annotation.contentCodec() == JsonCodec.NoJsonValueCodec.class
+ && annotation.keyCodec() == JsonCodec.NoMapKeyCodec.class
+ && annotation.valueCodec() == JsonCodec.NoJsonValueCodec.class;
+ }
+
+ private boolean registerJsonValueDeclarations(
+ DuringAnalysisAccess access, Class<?> type, JsonMixinView annotations) {
+ boolean hasValue = false;
+ for (Class<?> current = type;
+ current != null && current != Object.class;
+ current = current.getSuperclass()) {
+ for (Field field : current.getDeclaredFields()) {
+ if (annotation(annotations, field, JsonValue.class) != null) {
+ hasValue = true;
+ RuntimeReflection.register(field);
+ if (Runtime.version().feature() <= 24) {
+ access.registerAsUnsafeAccessed(field);
+ }
+ registerOccurrenceCodecs(annotations, field);
+ }
+ }
+ }
+ for (Method method : type.getMethods()) {
+ if (annotation(annotations, method, JsonValue.class) != null) {
+ hasValue = true;
+ RuntimeReflection.register(method);
+ registerOccurrenceCodecs(annotations, method);
+ }
+ }
+ for (Class<?> current = type;
+ current != null && current != Object.class;
+ current = current.getSuperclass()) {
+ for (Method method : current.getDeclaredMethods()) {
+ if (!Modifier.isPublic(method.getModifiers())
+ && annotation(annotations, method, JsonValue.class) != null) {
+ hasValue = true;
+ RuntimeReflection.register(method);
+ registerOccurrenceCodecs(annotations, method);
+ }
+ }
+ }
+ if (!hasValue) {
+ return false;
+ }
+ for (Constructor<?> constructor : type.getDeclaredConstructors()) {
+ if (annotation(annotations, constructor, JsonCreator.class) != null) {
+ RuntimeReflection.register(constructor);
+ }
+ }
+ for (Method method : type.getDeclaredMethods()) {
+ if (annotation(annotations, method, JsonCreator.class) != null) {
+ RuntimeReflection.register(method);
+ }
+ }
+ return true;
+ }
+
+ private void registerReflectiveDeclarations(Set<AnnotatedElement> declarations) {
+ for (AnnotatedElement declaration : declarations) {
+ if (declaration instanceof Field) {
+ RuntimeReflection.register((Field) declaration);
+ } else if (declaration instanceof Method) {
+ RuntimeReflection.register((Method) declaration);
+ } else if (declaration instanceof Constructor<?>) {
+ RuntimeReflection.register((Constructor<?>) declaration);
+ } else if (declaration instanceof Parameter) {
+ RuntimeReflection.register(((Parameter) declaration).getDeclaringExecutable());
+ }
+ }
+ }
+
+ private void registerGeneratedCodec(
+ DuringAnalysisAccess access, Class<?> type, Class<?> mixinType) {
+ String codecName =
+ mixinType == null
+ ? JsonSharedRegistry.generatedCodecBinaryName(type)
+ : JsonSharedRegistry.generatedMixinCodecBinaryName(mixinType, type);
Class<?> codecClass = access.findClassByName(codecName);
if (codecClass == null) {
return;
@@ -166,7 +327,7 @@ final class ForyJsonGraalVMFeature implements Feature {
throw new IllegalStateException(
"Generated JSON codec Record metadata does not match " + type.getName());
}
- GeneratedJsonCodecFactories.register(type, factory);
+ GeneratedJsonCodecFactories.register(type, mixinType, factory);
} catch (Throwable e) {
throw new IllegalStateException(
"Cannot initialize generated JSON codec factory " + factoryName, e);
@@ -178,7 +339,12 @@ final class ForyJsonGraalVMFeature implements Feature {
GeneratedJsonCodecFactories.freeze();
}
- private void registerModelHierarchy(BeforeAnalysisAccess access, Class<?> type) {
+ private void registerModelHierarchy(DuringAnalysisAccess access, Class<?> type) {
+ registerModelHierarchy(access, type, null);
+ }
+
+ private void registerModelHierarchy(
+ DuringAnalysisAccess access, Class<?> type, JsonMixinView annotations) {
TypeRef<?> ownerType = TypeRef.of(type);
boolean record = type.isRecord();
for (Class<?> current = type;
@@ -197,36 +363,74 @@ final class ForyJsonGraalVMFeature implements Feature {
if (!current.isRecord() && Runtime.version().feature() <= 24) {
access.registerAsUnsafeAccessed(field);
}
- registerOccurrenceCodecs(field);
- registerResolvedType(ownerType.resolveType(field.getGenericType()).getType());
+ registerOccurrenceCodecs(annotations, field);
+ Type resolvedType = ownerType.resolveType(field.getGenericType()).getType();
+ registerResolvedType(resolvedType);
+ if (annotation(annotations, field, JsonUnwrapped.class) != null) {
+ registerNestedModel(access, resolvedType);
+ }
}
}
}
for (Method method : type.getMethods()) {
- if (ObjectCodecBuilder.usesJsonMetadata(method, record)) {
+ boolean mixinSelector = hasMixinSelector(annotations, method);
+ if (ObjectCodecBuilder.usesJsonMetadata(method, record)
+ || mixinSelector) {
if (method.getDeclaringClass().isInterface()) {
RuntimeReflection.register(method);
}
- if (ObjectCodecBuilder.usesJsonReturn(method)) {
- registerOccurrenceCodecs(method);
- registerResolvedType(ownerType.resolveType(method.getGenericReturnType()).getType());
+ if (ObjectCodecBuilder.usesJsonReturn(method)
+ || mixinSelector && method.getReturnType() != void.class) {
+ registerOccurrenceCodecs(annotations, method);
+ Type resolvedType = ownerType.resolveType(method.getGenericReturnType()).getType();
+ registerResolvedType(resolvedType);
+ if (annotation(annotations, method, JsonUnwrapped.class) != null) {
+ registerNestedModel(access, resolvedType);
+ }
}
- if (ObjectCodecBuilder.usesJsonParameters(method)) {
- registerParameterCodecs(method.getParameters());
+ if (ObjectCodecBuilder.usesJsonParameters(method)
+ || mixinSelector && method.getParameterCount() != 0) {
+ registerParameterCodecs(annotations, method.getParameters());
registerResolvedParameterTypes(ownerType, method.getParameters());
+ registerUnwrappedParameters(access, ownerType, annotations, method.getParameters());
}
}
}
for (Constructor<?> constructor : type.getDeclaredConstructors()) {
- if (constructor.isAnnotationPresent(JsonCreator.class)) {
- registerParameterCodecs(constructor.getParameters());
+ if (annotation(annotations, constructor, JsonCreator.class) != null
+ || hasMixinSelector(annotations, constructor)) {
+ registerParameterCodecs(annotations, constructor.getParameters());
registerResolvedParameterTypes(ownerType, constructor.getParameters());
+ registerUnwrappedParameters(
+ access, ownerType, annotations, constructor.getParameters());
}
}
for (Method method : type.getDeclaredMethods()) {
- if (method.isAnnotationPresent(JsonCreator.class)) {
- registerParameterCodecs(method.getParameters());
+ if (annotation(annotations, method, JsonCreator.class) != null
+ || hasMixinSelector(annotations, method)) {
+ registerParameterCodecs(annotations, method.getParameters());
registerResolvedParameterTypes(ownerType, method.getParameters());
+ registerUnwrappedParameters(access, ownerType, annotations, method.getParameters());
+ }
+ }
+ }
+
+ private void registerNestedModel(DuringAnalysisAccess access, Type type) {
+ Class<?> rawType = rawType(type);
+ if (rawType != null && rawType != Object.class) {
+ registerModel(access, rawType);
+ }
+ }
+
+ private void registerUnwrappedParameters(
+ DuringAnalysisAccess access,
+ TypeRef<?> ownerType,
+ JsonMixinView annotations,
+ Parameter[] parameters) {
+ for (Parameter parameter : parameters) {
+ if (annotation(annotations, parameter, JsonUnwrapped.class) != null) {
+ registerNestedModel(
+ access, ownerType.resolveType(parameter.getParameterizedType()).getType());
}
}
}
@@ -249,19 +453,44 @@ final class ForyJsonGraalVMFeature implements Feature {
return changed;
}
- private void registerParameterCodecs(Parameter[] parameters) {
+ private void registerParameterCodecs(
+ JsonMixinView annotations, Parameter[] parameters) {
for (Parameter parameter : parameters) {
- registerCodecs(parameter.getDeclaredAnnotation(JsonCodec.class));
+ registerCodecs(annotation(annotations, parameter, JsonCodec.class));
}
}
- private void registerOccurrenceCodecs(AnnotatedElement element) {
- registerCodecs(element.getDeclaredAnnotation(JsonCodec.class));
- if (element.isAnnotationPresent(JsonBase64.class)) {
+ private void registerOccurrenceCodecs(
+ JsonMixinView annotations, AnnotatedElement element) {
+ registerCodecs(annotation(annotations, element, JsonCodec.class));
+ if (annotation(annotations, element, JsonBase64.class) != null) {
registerCodec(Base64ByteArrayCodec.class);
}
}
+ private static <A extends java.lang.annotation.Annotation> A annotation(
+ JsonMixinView annotations, AnnotatedElement element, Class<A> annotationType) {
+ return annotations == null
+ ? element.getDeclaredAnnotation(annotationType)
+ : annotations.annotation(element, annotationType);
+ }
+
+ private static boolean hasMixinSelector(JsonMixinView annotations, Executable executable) {
+ if (annotations == null) {
+ return false;
+ }
+ Set<AnnotatedElement> declarations = annotations.targetDeclarations();
+ if (declarations.contains(executable)) {
+ return true;
+ }
+ for (Parameter parameter : executable.getParameters()) {
+ if (declarations.contains(parameter)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
private void registerResolvedParameterTypes(TypeRef<?> ownerType, Parameter[] parameters) {
for (Parameter parameter : parameters) {
registerResolvedType(ownerType.resolveType(parameter.getParameterizedType()).getType());
@@ -335,15 +564,7 @@ final class ForyJsonGraalVMFeature implements Feature {
}
private boolean registerContainer(Type type) {
- Class<?> rawType = null;
- if (type instanceof Class<?>) {
- rawType = (Class<?>) type;
- } else if (type instanceof ParameterizedType) {
- Type parameterizedRawType = ((ParameterizedType) type).getRawType();
- if (parameterizedRawType instanceof Class<?>) {
- rawType = (Class<?>) parameterizedRawType;
- }
- }
+ Class<?> rawType = rawType(type);
if (rawType == null
|| rawType.isInterface()
|| Modifier.isAbstract(rawType.getModifiers())
@@ -362,11 +583,16 @@ final class ForyJsonGraalVMFeature implements Feature {
}
private void registerSubtypes(DuringAnalysisAccess access, Class<?> type) {
- JsonSubTypes annotation = type.getDeclaredAnnotation(JsonSubTypes.class);
- if (annotation == null) {
+ registerSubtypes(access, type, null);
+ }
+
+ private void registerSubtypes(
+ DuringAnalysisAccess access, Class<?> type, JsonMixinView annotations) {
+ JsonSubTypes subTypes = annotation(annotations, type, JsonSubTypes.class);
+ if (subTypes == null) {
return;
}
- for (JsonSubTypes.Type entry : annotation.value()) {
+ for (JsonSubTypes.Type entry : subTypes.value()) {
Class<?> subtype = entry.value();
if (subtype != Void.class) {
registerModel(access, subtype);
@@ -421,4 +647,15 @@ final class ForyJsonGraalVMFeature implements Feature {
&& field.getType() != Class.class
&& !field.isSynthetic();
}
+
+ private static Class<?> rawType(Type type) {
+ if (type instanceof Class<?>) {
+ return (Class<?>) type;
+ }
+ if (type instanceof ParameterizedType) {
+ Type rawType = ((ParameterizedType) type).getRawType();
+ return rawType instanceof Class<?> ? (Class<?>) rawType : null;
+ }
+ return null;
+ }
}
diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonAsyncCompilationTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonAsyncCompilationTest.java
index 2aabfb2a2..c3e8b9d73 100644
--- a/java/fory-json/src/test/java/org/apache/fory/json/JsonAsyncCompilationTest.java
+++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonAsyncCompilationTest.java
@@ -882,6 +882,7 @@ public class JsonAsyncCompilationTest {
1,
2 * 1024 * 1024,
codecs,
+ Collections.<Class<?>, Class<?>>emptyMap(),
null);
ControlledExecutor executor = new ControlledExecutor();
Constructor<JsonSharedRegistry> constructor =
diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonMixinTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonMixinTest.java
new file mode 100644
index 000000000..b84d7605f
--- /dev/null
+++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonMixinTest.java
@@ -0,0 +1,1133 @@
+/*
+ * 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.assertNotEquals;
+import static org.testng.Assert.assertThrows;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.UUID;
+import org.apache.fory.json.annotation.JsonAnyGetter;
+import org.apache.fory.json.annotation.JsonAnyProperty;
+import org.apache.fory.json.annotation.JsonAnySetter;
+import org.apache.fory.json.annotation.JsonBase64;
+import org.apache.fory.json.annotation.JsonCodec;
+import org.apache.fory.json.annotation.JsonCreator;
+import org.apache.fory.json.annotation.JsonIgnore;
+import org.apache.fory.json.annotation.JsonMixin;
+import org.apache.fory.json.annotation.JsonMixinRemove;
+import org.apache.fory.json.annotation.JsonProperty;
+import org.apache.fory.json.annotation.JsonPropertyOrder;
+import org.apache.fory.json.annotation.JsonRawValue;
+import org.apache.fory.json.annotation.JsonSubTypes;
+import org.apache.fory.json.annotation.JsonType;
+import org.apache.fory.json.annotation.JsonUnwrapped;
+import org.apache.fory.json.annotation.JsonValue;
+import org.apache.fory.json.codec.JsonValueCodec;
+import org.apache.fory.json.reader.Latin1JsonReader;
+import org.apache.fory.json.reader.Utf16JsonReader;
+import org.apache.fory.json.reader.Utf8JsonReader;
+import org.apache.fory.json.writer.StringJsonWriter;
+import org.apache.fory.json.writer.Utf8JsonWriter;
+import org.apache.fory.platform.JdkVersion;
+import org.apache.fory.reflect.TypeRef;
+import org.testng.SkipException;
+import org.testng.annotations.Factory;
+import org.testng.annotations.Test;
+
+public class JsonMixinTest extends ForyJsonTestModels {
+ @Factory(dataProvider = "enableCodegen")
+ public JsonMixinTest(boolean codegen) {
+ super(codegen);
+ }
+
+ @Test
+ public void propertyAnnotations() {
+ ForyJson json = newJsonBuilder().registerMixin(BasicMixin.class).build();
+ BasicTarget value = basic("alpha");
+ String expected =
+ "{\"display_name\":\"alpha\",\"body\":{\"ok\":true},\"bytes\":\"AQID\","
+ + "\"child_label\":\"kid\",\"ignored\":7}";
+ assertEquals(json.toJson(value), expected);
+ assertEquals(new String(json.toJsonBytes(value), StandardCharsets.UTF_8), expected);
+ assertEquals(json.toJson(value, BasicTarget.class), expected);
+
+ TypeRef<BasicTarget> type = new TypeRef<BasicTarget>() {};
+ assertEquals(json.toJson(value, type), expected);
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ json.writeJsonTo(value, type, output);
+ assertEquals(new String(output.toByteArray(), StandardCharsets.UTF_8), expected);
+
+ String latin =
+ "{\"display_name\":\"latin\",\"body\":\"text\",\"bytes\":\"AQID\","
+ + "\"child_label\":\"child\",\"ignored\":99}";
+ BasicTarget latinValue = json.fromJson(latin, BasicTarget.class);
+ assertBasic(latinValue, "latin", "text", "child");
+ assertEquals(latinValue.ignored, 0);
+
+ String unicode = latin.replace("latin", "你好");
+ assertBasic(json.fromJson(unicode, type), "你好", "text", "child");
+ assertBasic(
+ json.fromJson(latin.getBytes(StandardCharsets.UTF_8), BasicTarget.class),
+ "latin",
+ "text",
+ "child");
+ assertGeneratedWhenSupported(json, BasicTarget.class);
+ }
+
+ @Test
+ public void anyAnnotations() {
+ ForyJson fieldJson = newJsonBuilder().registerMixin(AnyFieldMixin.class).build();
+ AnyFieldTarget field = new AnyFieldTarget();
+ field.extra.put("dynamic", "one");
+ assertEquals(fieldJson.toJson(field), "{\"dynamic\":\"A:one\"}");
+ assertEquals(
+ fieldJson.fromJson("{\"dynamic\":\"A:two\"}", AnyFieldTarget.class).extra.get("dynamic"),
+ "two");
+
+ ForyJson methodJson = newJsonBuilder().registerMixin(AnyMethodMixin.class).build();
+ AnyMethodTarget method = new AnyMethodTarget();
+ method.extra.put("dynamic", "three");
+ assertEquals(methodJson.toJson(method), "{\"dynamic\":\"A:three\"}");
+ assertEquals(
+ methodJson.fromJson("{\"dynamic\":\"A:four\"}", AnyMethodTarget.class).extra.get("dynamic"),
+ "four");
+ assertGeneratedWhenSupported(fieldJson, AnyFieldTarget.class);
+ assertGeneratedWhenSupported(methodJson, AnyMethodTarget.class);
+ }
+
+ @Test
+ public void creatorsAndValue() {
+ ForyJson constructorJson =
+ newJsonBuilder().registerMixin(ConstructorCreatorMixin.class).build();
+ CreatorTarget constructor =
+ constructorJson.fromJson("{\"id\":1,\"name\":\"one\"}", CreatorTarget.class);
+ assertEquals(constructor.route, "constructor");
+ assertEquals(constructorJson.toJson(constructor), "{\"id\":1,\"name\":\"one\"}");
+
+ ForyJson factoryJson = newJsonBuilder().registerMixin(FactoryCreatorMixin.class).build();
+ CreatorTarget factory =
+ factoryJson.fromJson("{\"id\":2,\"name\":\"two\"}", CreatorTarget.class);
+ assertEquals(factory.route, "factory");
+
+ ForyJson valueJson = newJsonBuilder().registerMixin(ValueMixin.class).build();
+ assertEquals(valueJson.toJson(new ValueTarget("write")), "\"write\"");
+ ValueTarget decoded = valueJson.fromJson("\"read\"", ValueTarget.class);
+ assertEquals(decoded.text(), "read");
+ assertEquals(decoded.route, "factory");
+ }
+
+ @Test
+ public void typeAnnotations() {
+ ForyJson subtypeJson = newJsonBuilder().registerMixin(ShapeMixin.class).build();
+ Shape value = new Circle(3);
+ assertEquals(subtypeJson.toJson(value, Shape.class), "{\"kind\":\"circle\",\"radius\":3}");
+ Shape decoded = subtypeJson.fromJson("{\"kind\":\"circle\",\"radius\":4}", Shape.class);
+ assertTrue(decoded instanceof Circle);
+ assertEquals(((Circle) decoded).radius, 4);
+
+ ForyJson codecJson = newJsonBuilder().registerMixin(WholeTargetMixin.class).build();
+ assertEquals(codecJson.toJson(new WholeTarget("write")), "\"whole:write\"");
+ assertEquals(codecJson.fromJson("\"whole:read\"", WholeTarget.class).value, "read");
+
+ UUID uuid = UUID.fromString("0d57bb7d-e50e-4a4f-9d59-d159c48086ae");
+ ForyJson uuidJson = newJsonBuilder().registerMixin(UuidMixin.class).build();
+ assertEquals(uuidJson.toJson(uuid), "\"uuid:" + uuid + "\"");
+ assertEquals(uuidJson.fromJson("\"uuid:" + uuid + "\"", UUID.class), uuid);
+ }
+
+ @Test
+ public void registrationLifecycle() {
+ ForyJson direct = newJsonBuilder().build();
+ ForyJsonBuilder builder = newJsonBuilder().registerMixin(FirstNameMixin.class);
+ ForyJson first = builder.build();
+ builder.registerMixin(SecondNameMixin.class);
+ ForyJson second = builder.build();
+
+ assertEquals(direct.toJson(new NameTarget("value")), "{\"name\":\"value\"}");
+ assertEquals(first.toJson(new NameTarget("value")), "{\"first\":\"value\"}");
+ assertEquals(second.toJson(new NameTarget("value")), "{\"second\":\"value\"}");
+ assertEquals(first.toJson(new NameTarget("again")), "{\"first\":\"again\"}");
+
+ ForyJson reset =
+ newJsonBuilder()
+ .registerMixin(FirstNameMixin.class)
+ .registerMixin(EmptyNameMixin.class)
+ .build();
+ assertEquals(reset.toJson(new NameTarget("value")), "{\"name\":\"value\"}");
+
+ ForyJson replacedInvalid =
+ newJsonBuilder().registerMixin(ConcreteMixin.class).registerMixin(BasicMixin.class).build();
+ assertTrue(replacedInvalid.toJson(basic("valid")).contains("\"display_name\":\"valid\""));
+
+ ForyJson repeated =
+ newJsonBuilder()
+ .registerMixin(FirstNameMixin.class)
+ .registerMixin(FirstNameMixin.class)
+ .build();
+ ForyJson equivalent = newJsonBuilder().registerMixin(FirstNameMixin.class).build();
+ assertEquals(JsonTestSupport.config(repeated), JsonTestSupport.config(equivalent));
+ assertEquals(
+ JsonTestSupport.config(repeated).getCodegenHash(),
+ JsonTestSupport.config(equivalent).getCodegenHash());
+ assertNotEquals(JsonTestSupport.config(first), JsonTestSupport.config(second));
+ assertNotEquals(
+ JsonTestSupport.config(first).getCodegenHash(),
+ JsonTestSupport.config(second).getCodegenHash());
+ assertGeneratedWhenSupported(first, NameTarget.class);
+ assertGeneratedWhenSupported(second, NameTarget.class);
+ }
+
+ @Test
+ public void exactTargets() {
+ ForyJson parentJson = newJsonBuilder().registerMixin(ExactParentMixin.class).build();
+ assertEquals(parentJson.toJson(new ExactParent()), "{\"parent_name\":\"parent\"}");
+ assertEquals(parentJson.toJson(new ExactChild()), "{\"name\":\"parent\",\"rank\":2}");
+
+ ForyJson childJson = newJsonBuilder().registerMixin(ExactChildMixin.class).build();
+ assertEquals(childJson.toJson(new ExactParent()), "{\"name\":\"parent\"}");
+ assertEquals(childJson.toJson(new ExactChild()), "{\"child_name\":\"parent\",\"rank\":2}");
+
+ ForyJson nestedJson =
+ newJsonBuilder()
+ .registerMixin(BasicMixin.class)
+ .registerMixin(BasicChildMixin.class)
+ .build();
+ assertEquals(
+ nestedJson.toJson(basic("nested")),
+ "{\"display_name\":\"nested\",\"body\":{\"ok\":true},\"bytes\":\"AQID\","
+ + "\"child_caption\":\"kid\",\"ignored\":7}");
+ }
+
+ @Test
+ public void replacementAndRemoval() {
+ ForyJson replacement = newJsonBuilder().registerMixin(ReplacementMixin.class).build();
+ ReplacementTarget replacementValue = new ReplacementTarget();
+ replacementValue.value = "value";
+ assertEquals(
+ replacement.toJson(replacementValue), "{\"mixed\":\"value\",\"new_label\":\"kid\"}");
+ replacementValue.value = null;
+ assertEquals(replacement.toJson(replacementValue), "{\"new_label\":\"kid\"}");
+ ReplacementTarget replacementDecoded =
+ replacement.fromJson(
+ "{\"mixed\":\"read\",\"new_label\":\"child\"}", ReplacementTarget.class);
+ assertEquals(replacementDecoded.value, "read");
+ assertEquals(replacementDecoded.child.label, "child");
+
+ ForyJson representation =
+ newJsonBuilder().registerMixin(RepresentationRemoveMixin.class).build();
+ assertEquals(
+ representation.toJson(new RepresentationRemoveTarget()),
+ "{\"name\":\"name\",\"raw\":\"1\",\"bytes\":[1],"
+ + "\"child\":{\"label\":\"kid\"},\"hidden\":7}");
+
+ ForyJson anyField = newJsonBuilder().registerMixin(AnyFieldRemoveMixin.class).build();
+ assertEquals(anyField.toJson(new AnyFieldRemoveTarget()), "{\"extra\":{\"x\":1}}");
+
+ ForyJson anyMethods = newJsonBuilder().registerMixin(AnyMethodRemoveMixin.class).build();
+ assertEquals(anyMethods.toJson(new AnyMethodRemoveTarget()), "{\"extra\":{\"x\":1}}");
+ AnyMethodRemoveTarget anyDecoded =
+ anyMethods.fromJson("{\"unknown\":2}", AnyMethodRemoveTarget.class);
+ assertEquals(anyDecoded.extra, map("x", 1));
+
+ ForyJson value = newJsonBuilder().registerMixin(ValueRemoveMixin.class).build();
+ assertEquals(value.toJson(new ValueRemoveTarget("write")), "{\"text\":\"write\"}");
+ assertEquals(value.fromJson("{\"text\":\"read\"}", ValueRemoveTarget.class).text, "read");
+
+ ForyJson creator = newJsonBuilder().registerMixin(CreatorRemoveMixin.class).build();
+ CreatorRemoveTarget creatorValue = creator.fromJson("{\"id\":5}", CreatorRemoveTarget.class);
+ assertEquals(creatorValue.id, 5);
+ assertEquals(creatorValue.route, "default");
+
+ ForyJson subtype = newJsonBuilder().registerMixin(ShapeRemoveMixin.class).build();
+ assertThrows(
+ ForyJsonException.class, () -> subtype.toJson(new RemovedCircle(), RemovedShape.class));
+
+ ForyJson codec = newJsonBuilder().registerMixin(CodecBarrierMixin.class).build();
+ assertEquals(newJson().toJson(new CodecBarrierChild()), "\"inherited\"");
+ assertEquals(codec.toJson(new CodecBarrierChild()), "{\"name\":\"child\"}");
+
+ ForyJson order = newJsonBuilder().registerMixin(OrderBarrierMixin.class).build();
+ assertEquals(newJson().toJson(new OrderBarrierChild()), "{\"b\":2,\"a\":1}");
+ assertEquals(order.toJson(new OrderBarrierChild()), "{\"a\":1,\"b\":2}");
+ }
+
+ @Test
+ public void matching() {
+ ForyJson overload = newJsonBuilder().registerMixin(OverloadMixin.class).build();
+ OverloadTarget value = overload.fromJson("{\"text\":\"value\"}", OverloadTarget.class);
+ assertEquals(value.value, "value");
+ assertEquals(overload.toJson(value), "{\"text\":\"value\"}");
+
+ ForyJson helper = newJsonBuilder().registerMixin(HelperMixin.class).build();
+ assertEquals(helper.toJson(new SelectorTarget()), "{\"name\":\"target\"}");
+
+ assertThrows(NullPointerException.class, () -> newJsonBuilder().registerMixin(null));
+ assertRegistrationInvalid(BasicTarget.class);
+ assertStructureInvalid(ConcreteMixin.class);
+ assertStructureInvalid(SourceHierarchyMixin.class);
+ assertStructureInvalid(PrimitiveTargetMixin.class);
+ assertStructureInvalid(SelfMixin.class);
+ @JsonMixin(target = BasicTarget.class)
+ abstract class LocalMixin {}
+ assertStructureInvalid(LocalMixin.class);
+ assertStructureInvalid(UnmatchedFieldMixin.class);
+ assertStructureInvalid(ReturnTypeMixin.class);
+ assertStructureInvalid(HiddenFieldMixin.class);
+ assertStructureInvalid(StaticFieldMixin.class);
+ assertStructureInvalid(ConcreteMethodMixin.class);
+ assertStructureInvalid(JsonTypeMixin.class);
+ assertStructureInvalid(RemoveJsonTypeMixin.class);
+ assertStructureInvalid(EmptyRemoveMixin.class);
+ assertStructureInvalid(DuplicateRemoveMixin.class);
+ assertStructureInvalid(UnsupportedRemoveMixin.class);
+ assertStructureInvalid(IllegalRemoveMixin.class);
+ assertStructureInvalid(AddRemoveMixin.class);
+ }
+
+ @Test
+ public void semanticDiagnostics() {
+ assertPairFailure(InvalidTypeCodecMixin.class, InvalidTypeCodecTarget.class);
+ assertPairFailure(InvalidSubTypesMixin.class, InvalidSubTypesTarget.class);
+ assertPairFailure(InvalidValueMixin.class, InvalidValueTarget.class);
+ assertPairFailure(ObjectMethodMixin.class, ObjectMethodTarget.class);
+
+ ForyJson intrinsic = newJsonBuilder().registerMixin(IntrinsicMemberMixin.class).build();
+ assertEquals(intrinsic.toJson(IntrinsicMemberTarget.VALUE), "\"VALUE\"");
+
+ ForyJson registered =
+ newJsonBuilder()
+ .registerCodec(WholeTarget.class, new WholeTargetCodec("registered:"))
+ .registerMixin(WholeTargetMixin.class)
+ .build();
+ assertEquals(registered.toJson(new WholeTarget("value")), "\"registered:value\"");
+ assertEquals(registered.fromJson("\"registered:read\"", WholeTarget.class).value, "read");
+ }
+
+ @Test
+ public void directRemoveRejected() {
+ for (Class<?> type :
+ new Class<?>[] {
+ DirectTypeRemove.class,
+ DirectFieldRemove.class,
+ DirectMethodRemove.class,
+ DirectConstructorRemove.class,
+ DirectParameterRemove.class,
+ DirectEnumRemove.class
+ }) {
+ ForyJsonException failure =
+ expectThrows(ForyJsonException.class, () -> newJson().fromJson("{}", type));
+ assertTrue(failure.getMessage().contains("@JsonMixinRemove"), failure.getMessage());
+ }
+ }
+
+ @Test
+ public void directParameterAnnotation() {
+ DirectParameterTarget value = new DirectParameterTarget();
+ value.id = 3;
+ assertEquals(newJson().toJson(value), "{\"id\":3}");
+ }
+
+ private void assertPairFailure(Class<?> mixinType, Class<?> targetType) {
+ ForyJson json = newJsonBuilder().registerMixin(mixinType).build();
+ ForyJsonException failure =
+ expectThrows(ForyJsonException.class, () -> json.fromJson("{}", targetType));
+ String message = failure.getMessage();
+ assertTrue(message.contains(targetType.getName()), message);
+ assertTrue(message.contains(mixinType.getName()), message);
+ }
+
+ @Test
+ public void recordSelectors() throws Exception {
+ if (JdkVersion.MAJOR_VERSION < 17) {
+ throw new SkipException("Java record test requires JDK 17+");
+ }
+ String simpleName =
+ codegenEnabled() ? "JsonMixinGeneratedRecord" : "JsonMixinInterpretedRecord";
+ String mixinName = simpleName + "Mixin";
+ Class<?> type =
+ compileRecordClass(
+ simpleName,
+ "package org.apache.fory.json.records;\n"
+ + "import org.apache.fory.json.annotation.*;\n"
+ + "public record "
+ + simpleName
+ + "(String name, byte[] bytes) {}\n"
+ + "@JsonMixin(target = "
+ + simpleName
+ + ".class)\n"
+ + "@JsonPropertyOrder({\"display_name\", \"bytes\"})\n"
+ + "abstract class "
+ + mixinName
+ + " {\n"
+ + " @JsonProperty(\"display_name\") String name;\n"
+ + " @JsonBase64 byte[] bytes;\n"
+ + " "
+ + mixinName
+ + "(\n"
+ + " @JsonProperty(\"display_name\") String name, byte[] bytes) {}\n"
+ + "}\n");
+ Class<?> mixin =
+ Class.forName("org.apache.fory.json.records." + mixinName, true, type.getClassLoader());
+ Object record =
+ type.getConstructor(String.class, byte[].class).newInstance("record", new byte[] {1, 2, 3});
+ ForyJson json = newJsonBuilder().registerMixin(mixin).build();
+ assertEquals(json.toJson(record), "{\"display_name\":\"record\",\"bytes\":\"AQID\"}");
+ Object decoded = json.fromJson("{\"display_name\":\"read\",\"bytes\":\"AQID\"}", type);
+ assertEquals(type.getMethod("name").invoke(decoded), "read");
+ assertEquals(type.getMethod("bytes").invoke(decoded), new byte[] {1, 2, 3});
+ assertGeneratedWhenSupported(json, type);
+ }
+
+ private void assertRegistrationInvalid(Class<?> mixin) {
+ assertThrows(IllegalArgumentException.class, () -> newJsonBuilder().registerMixin(mixin));
+ }
+
+ private void assertStructureInvalid(Class<?> mixin) {
+ assertThrows(ForyJsonException.class, () -> newJsonBuilder().registerMixin(mixin).build());
+ }
+
+ private static BasicTarget basic(String name) {
+ BasicTarget value = new BasicTarget();
+ value.name = name;
+ value.body = "{\"ok\":true}";
+ value.bytes = new byte[] {1, 2, 3};
+ value.child = new BasicChild("kid");
+ value.ignored = 7;
+ return value;
+ }
+
+ private static void assertBasic(BasicTarget value, String name, String body, String child) {
+ assertEquals(value.name, name);
+ assertEquals(value.body, body);
+ assertEquals(value.bytes, new byte[] {1, 2, 3});
+ assertEquals(value.child.label, child);
+ }
+
+ private static Map<String, Integer> map(String name, int value) {
+ Map<String, Integer> result = new LinkedHashMap<>();
+ result.put(name, value);
+ return result;
+ }
+
+ public static final class BasicTarget {
+ public String name;
+ public String body;
+ public byte[] bytes;
+ public BasicChild child;
+ public int ignored;
+ }
+
+ public static final class BasicChild {
+ public String label;
+
+ public BasicChild() {}
+
+ BasicChild(String label) {
+ this.label = label;
+ }
+ }
+
+ @JsonMixin(target = BasicTarget.class)
+ @JsonPropertyOrder({"display_name", "body", "bytes", "child", "ignored"})
+ public abstract static class BasicMixin {
+ @JsonProperty("display_name")
+ String name;
+
+ @JsonRawValue String body;
+ @JsonBase64 byte[] bytes;
+
+ @JsonUnwrapped(prefix = "child_")
+ BasicChild child;
+
+ @JsonIgnore(ignoreRead = true, ignoreWrite = false)
+ int ignored;
+ }
+
+ @JsonMixin(target = BasicChild.class)
+ public abstract static class BasicChildMixin {
+ @JsonProperty("caption")
+ String label;
+ }
+
+ public static final class AnyFieldTarget {
+ public Map<String, String> extra = new LinkedHashMap<>();
+ }
+
+ @JsonMixin(target = AnyFieldTarget.class)
+ public abstract static class AnyFieldMixin {
+ @JsonAnyProperty
+ @JsonCodec(valueCodec = JsonCodecAnnotationTest.AStringCodec.class)
+ Map<String, String> extra;
+ }
+
+ public static final class AnyMethodTarget {
+ private final Map<String, String> extra = new LinkedHashMap<>();
+
+ public Map<String, String> getExtra() {
+ return extra;
+ }
+
+ public void put(String name, String value) {
+ extra.put(name, value);
+ }
+ }
+
+ @JsonMixin(target = AnyMethodTarget.class)
+ public interface AnyMethodMixin {
+ @JsonAnyGetter
+ @JsonCodec(valueCodec = JsonCodecAnnotationTest.AStringCodec.class)
+ Map<String, String> getExtra();
+
+ @JsonAnySetter
+ void put(String name, @JsonCodec(JsonCodecAnnotationTest.AStringCodec.class) String value);
+ }
+
+ public static final class CreatorTarget {
+ public final int id;
+ public final String name;
+
+ @JsonIgnore public final String route;
+
+ public CreatorTarget(int id, String name) {
+ this(id, name, "constructor");
+ }
+
+ private CreatorTarget(int id, String name, String route) {
+ this.id = id;
+ this.name = name;
+ this.route = route;
+ }
+
+ public static CreatorTarget create(int id, String name) {
+ return new CreatorTarget(id, name, "factory");
+ }
+ }
+
+ @JsonMixin(target = CreatorTarget.class)
+ public abstract static class ConstructorCreatorMixin {
+ @JsonCreator({"id", "name"})
+ ConstructorCreatorMixin(int id, String name) {}
+ }
+
+ @JsonMixin(target = CreatorTarget.class)
+ public interface FactoryCreatorMixin {
+ @JsonCreator({"id", "name"})
+ CreatorTarget create(int id, String name);
+ }
+
+ public static final class ValueTarget {
+ @JsonIgnore public final String route;
+ private final String value;
+
+ public ValueTarget(String value) {
+ this(value, "constructor");
+ }
+
+ private ValueTarget(String value, String route) {
+ this.value = value;
+ this.route = route;
+ }
+
+ public String text() {
+ return value;
+ }
+
+ public static ValueTarget create(String value) {
+ return new ValueTarget(value, "factory");
+ }
+ }
+
+ @JsonMixin(target = ValueTarget.class)
+ public interface ValueMixin {
+ @JsonValue
+ String text();
+
+ @JsonCreator
+ ValueTarget create(String value);
+ }
+
+ public interface Shape {}
+
+ public static final class Circle implements Shape {
+ public int radius;
+
+ public Circle() {}
+
+ Circle(int radius) {
+ this.radius = radius;
+ }
+ }
+
+ @JsonMixin(target = Shape.class)
+ @JsonSubTypes(
+ property = "kind",
+ value = {@JsonSubTypes.Type(value = Circle.class, name = "circle")})
+ public interface ShapeMixin {}
+
+ public static final class WholeTarget {
+ public String value;
+
+ public WholeTarget() {}
+
+ WholeTarget(String value) {
+ this.value = value;
+ }
+ }
+
+ @JsonMixin(target = WholeTarget.class)
+ @JsonCodec(WholeTargetCodec.class)
+ public interface WholeTargetMixin {}
+
+ public static final class WholeTargetCodec implements JsonValueCodec<WholeTarget> {
+ private final String prefix;
+
+ public WholeTargetCodec() {
+ this("whole:");
+ }
+
+ WholeTargetCodec(String prefix) {
+ this.prefix = prefix;
+ }
+
+ @Override
+ public void writeString(StringJsonWriter writer, WholeTarget value) {
+ writer.writeString(prefix + value.value);
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, WholeTarget value) {
+ writer.writeString(prefix + value.value);
+ }
+
+ @Override
+ public WholeTarget readLatin1(Latin1JsonReader reader) {
+ return read(reader.readString());
+ }
+
+ @Override
+ public WholeTarget readUtf16(Utf16JsonReader reader) {
+ return read(reader.readString());
+ }
+
+ @Override
+ public WholeTarget readUtf8(Utf8JsonReader reader) {
+ return read(reader.readString());
+ }
+
+ private WholeTarget read(String value) {
+ return new WholeTarget(value.substring(prefix.length()));
+ }
+ }
+
+ @JsonMixin(target = UUID.class)
+ @JsonCodec(UuidCodec.class)
+ public interface UuidMixin {}
+
+ public static final class UuidCodec implements JsonValueCodec<UUID> {
+ @Override
+ public void writeString(StringJsonWriter writer, UUID value) {
+ writer.writeString("uuid:" + value);
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, UUID value) {
+ writer.writeString("uuid:" + value);
+ }
+
+ @Override
+ public UUID readLatin1(Latin1JsonReader reader) {
+ return read(reader.readString());
+ }
+
+ @Override
+ public UUID readUtf16(Utf16JsonReader reader) {
+ return read(reader.readString());
+ }
+
+ @Override
+ public UUID readUtf8(Utf8JsonReader reader) {
+ return read(reader.readString());
+ }
+
+ private UUID read(String value) {
+ return UUID.fromString(value.substring("uuid:".length()));
+ }
+ }
+
+ public static final class NameTarget {
+ public String name;
+
+ NameTarget(String name) {
+ this.name = name;
+ }
+ }
+
+ @JsonMixin(target = NameTarget.class)
+ public abstract static class FirstNameMixin {
+ @JsonProperty("first")
+ String name;
+ }
+
+ @JsonMixin(target = NameTarget.class)
+ public abstract static class SecondNameMixin {
+ @JsonProperty("second")
+ String name;
+ }
+
+ @JsonMixin(target = NameTarget.class)
+ public interface EmptyNameMixin {}
+
+ public static class ExactParent {
+ public String name = "parent";
+ }
+
+ public static final class ExactChild extends ExactParent {
+ public int rank = 2;
+ }
+
+ @JsonMixin(target = ExactParent.class)
+ public abstract static class ExactParentMixin {
+ @JsonProperty("parent_name")
+ String name;
+ }
+
+ @JsonMixin(target = ExactChild.class)
+ public abstract static class ExactChildMixin {
+ @JsonProperty("child_name")
+ String name;
+ }
+
+ public static final class ReplacementTarget {
+ @JsonProperty(value = "direct", index = 3, include = JsonProperty.Include.ALWAYS)
+ public String value;
+
+ @JsonUnwrapped(prefix = "old_", suffix = "_old")
+ public BasicChild child = new BasicChild("kid");
+ }
+
+ @JsonMixin(target = ReplacementTarget.class)
+ public abstract static class ReplacementMixin {
+ @JsonProperty("mixed")
+ String value;
+
+ @JsonUnwrapped(prefix = "new_")
+ BasicChild child;
+ }
+
+ public static final class RepresentationRemoveTarget {
+ @JsonProperty("renamed")
+ public String name = "name";
+
+ @JsonRawValue public String raw = "1";
+ @JsonBase64 public byte[] bytes = new byte[] {1};
+
+ @JsonUnwrapped(prefix = "child_")
+ public BasicChild child = new BasicChild("kid");
+
+ @JsonIgnore public int hidden = 7;
+ }
+
+ @JsonMixin(target = RepresentationRemoveTarget.class)
+ public abstract static class RepresentationRemoveMixin {
+ @JsonMixinRemove(JsonProperty.class)
+ String name;
+
+ @JsonMixinRemove(JsonRawValue.class)
+ String raw;
+
+ @JsonMixinRemove(JsonBase64.class)
+ byte[] bytes;
+
+ @JsonMixinRemove(JsonUnwrapped.class)
+ BasicChild child;
+
+ @JsonMixinRemove(JsonIgnore.class)
+ int hidden;
+ }
+
+ public static final class AnyFieldRemoveTarget {
+ @JsonAnyProperty public Map<String, Integer> extra = map("x", 1);
+ }
+
+ @JsonMixin(target = AnyFieldRemoveTarget.class)
+ public abstract static class AnyFieldRemoveMixin {
+ @JsonMixinRemove(JsonAnyProperty.class)
+ Map<String, Integer> extra;
+ }
+
+ public static final class AnyMethodRemoveTarget {
+ final Map<String, Integer> extra = map("x", 1);
+
+ @JsonAnyGetter
+ public Map<String, Integer> getExtra() {
+ return extra;
+ }
+
+ @JsonAnySetter
+ public void put(String name, Integer value) {
+ extra.put(name, value);
+ }
+ }
+
+ @JsonMixin(target = AnyMethodRemoveTarget.class)
+ public interface AnyMethodRemoveMixin {
+ @JsonMixinRemove(JsonAnyGetter.class)
+ Map<String, Integer> getExtra();
+
+ @JsonMixinRemove(JsonAnySetter.class)
+ void put(String name, Integer value);
+ }
+
+ public static final class ValueRemoveTarget {
+ @JsonValue public String text;
+
+ public ValueRemoveTarget() {}
+
+ @JsonCreator
+ public ValueRemoveTarget(String text) {
+ this.text = text;
+ }
+ }
+
+ @JsonMixin(target = ValueRemoveTarget.class)
+ public abstract static class ValueRemoveMixin {
+ @JsonMixinRemove(JsonValue.class)
+ String text;
+
+ @JsonMixinRemove(JsonCreator.class)
+ ValueRemoveMixin(String text) {}
+ }
+
+ public static final class CreatorRemoveTarget {
+ public int id;
+ @JsonIgnore public String route;
+
+ public CreatorRemoveTarget() {
+ route = "default";
+ }
+
+ @JsonCreator({"id"})
+ public CreatorRemoveTarget(int id) {
+ this.id = id;
+ route = "creator";
+ }
+ }
+
+ @JsonMixin(target = CreatorRemoveTarget.class)
+ public abstract static class CreatorRemoveMixin {
+ @JsonMixinRemove(JsonCreator.class)
+ CreatorRemoveMixin(int id) {}
+ }
+
+ @JsonSubTypes(
+ property = "kind",
+ value = {@JsonSubTypes.Type(value = RemovedCircle.class, name = "circle")})
+ public interface RemovedShape {}
+
+ public static final class RemovedCircle implements RemovedShape {
+ public int radius = 1;
+ }
+
+ @JsonMixin(target = RemovedShape.class)
+ @JsonMixinRemove(JsonSubTypes.class)
+ public interface ShapeRemoveMixin {}
+
+ @JsonCodec(InheritedCodec.class)
+ public static class CodecBarrierParent {
+ public String name = "parent";
+ }
+
+ public static final class CodecBarrierChild extends CodecBarrierParent {
+ CodecBarrierChild() {
+ name = "child";
+ }
+ }
+
+ public static final class InheritedCodec implements JsonValueCodec<CodecBarrierParent> {
+ @Override
+ public void writeString(StringJsonWriter writer, CodecBarrierParent value) {
+ writer.writeString("inherited");
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, CodecBarrierParent value) {
+ writer.writeString("inherited");
+ }
+
+ @Override
+ public CodecBarrierParent readLatin1(Latin1JsonReader reader) {
+ reader.skipValue();
+ return new CodecBarrierParent();
+ }
+
+ @Override
+ public CodecBarrierParent readUtf16(Utf16JsonReader reader) {
+ reader.skipValue();
+ return new CodecBarrierParent();
+ }
+
+ @Override
+ public CodecBarrierParent readUtf8(Utf8JsonReader reader) {
+ reader.skipValue();
+ return new CodecBarrierParent();
+ }
+ }
+
+ @JsonMixin(target = CodecBarrierChild.class)
+ @JsonMixinRemove(JsonCodec.class)
+ public interface CodecBarrierMixin {}
+
+ @JsonPropertyOrder({"b", "a"})
+ public static class OrderBarrierParent {
+ public int a = 1;
+ public int b = 2;
+ }
+
+ public static final class OrderBarrierChild extends OrderBarrierParent {}
+
+ @JsonMixin(target = OrderBarrierChild.class)
+ @JsonMixinRemove(JsonPropertyOrder.class)
+ public interface OrderBarrierMixin {}
+
+ public static final class OverloadTarget {
+ String value;
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ public static void setValue(int value) {
+ throw new AssertionError(value);
+ }
+ }
+
+ @JsonMixin(target = OverloadTarget.class)
+ public interface OverloadMixin {
+ @JsonProperty("text")
+ void setValue(String value);
+ }
+
+ public static final class SelectorTarget {
+ public String name = "target";
+ }
+
+ public static final class InvalidTypeCodecTarget {}
+
+ @JsonMixin(target = InvalidTypeCodecTarget.class)
+ @JsonCodec(elementCodec = JsonCodecAnnotationTest.AStringCodec.class)
+ public interface InvalidTypeCodecMixin {}
+
+ public static final class InvalidSubTypesTarget {}
+
+ @JsonMixin(target = InvalidSubTypesTarget.class)
+ @JsonSubTypes({@JsonSubTypes.Type(value = InvalidSubTypesTarget.class, name = "value")})
+ public interface InvalidSubTypesMixin {}
+
+ public static final class InvalidValueTarget {
+ public String first() {
+ return "first";
+ }
+
+ public String second() {
+ return "second";
+ }
+ }
+
+ @JsonMixin(target = InvalidValueTarget.class)
+ public interface InvalidValueMixin {
+ @JsonValue
+ String first();
+
+ @JsonValue
+ String second();
+ }
+
+ public abstract static class SourceHierarchyParent {
+ @JsonProperty("inherited")
+ String name;
+ }
+
+ @JsonMixin(target = SelectorTarget.class)
+ public abstract static class SourceHierarchyMixin extends SourceHierarchyParent {
+ String unmatchedHelper;
+ }
+
+ @JsonMixin(target = SelectorTarget.class)
+ public abstract static class HelperMixin {
+ String unmatchedHelper;
+ }
+
+ @JsonMixin(target = BasicTarget.class)
+ public static final class ConcreteMixin {}
+
+ @JsonMixin(target = int.class)
+ public abstract static class PrimitiveTargetMixin {}
+
+ @JsonMixin(target = SelfMixin.class)
+ public abstract static class SelfMixin {}
+
+ @JsonMixin(target = BasicTarget.class)
+ public abstract static class UnmatchedFieldMixin {
+ @JsonProperty("missing")
+ long missing;
+ }
+
+ @JsonMixin(target = SelectorMethodTarget.class)
+ public interface ReturnTypeMixin {
+ @JsonProperty("name")
+ CharSequence getName();
+ }
+
+ public static final class SelectorMethodTarget {
+ public String getName() {
+ return "name";
+ }
+ }
+
+ public static final class ObjectMethodTarget {
+ public int id;
+ }
+
+ @JsonMixin(target = ObjectMethodTarget.class)
+ public abstract static class ObjectMethodMixin {
+ @JsonCodec(JsonCodecAnnotationTest.AStringCodec.class)
+ public abstract String toString();
+ }
+
+ public enum IntrinsicMemberTarget {
+ VALUE;
+
+ String label = "value";
+ }
+
+ @JsonMixin(target = IntrinsicMemberTarget.class)
+ public abstract static class IntrinsicMemberMixin {
+ @JsonProperty("name")
+ String label;
+ }
+
+ @JsonMixinRemove(JsonPropertyOrder.class)
+ public static final class DirectTypeRemove {}
+
+ public static final class DirectFieldRemove {
+ @JsonMixinRemove(JsonIgnore.class)
+ public int id;
+ }
+
+ public static final class DirectMethodRemove {
+ @JsonMixinRemove(JsonProperty.class)
+ public int getId() {
+ return 0;
+ }
+ }
+
+ public static final class DirectConstructorRemove {
+ @JsonMixinRemove(JsonCreator.class)
+ public DirectConstructorRemove() {}
+ }
+
+ public static final class DirectParameterRemove {
+ @JsonCreator
+ public DirectParameterRemove(@JsonProperty("id") @JsonMixinRemove(JsonProperty.class) int id) {}
+ }
+
+ public static final class DirectParameterTarget {
+ public int id;
+
+ public void ignored(@JsonProperty("ignored") String value) {}
+ }
+
+ @JsonMixinRemove(JsonPropertyOrder.class)
+ public enum DirectEnumRemove {
+ VALUE
+ }
+
+ public static class HiddenFieldParent {
+ public String name;
+ }
+
+ public static final class HiddenFieldChild extends HiddenFieldParent {
+ public String name;
+ }
+
+ @JsonMixin(target = HiddenFieldChild.class)
+ public abstract static class HiddenFieldMixin {
+ @JsonProperty("name")
+ String name;
+ }
+
+ @JsonMixin(target = BasicTarget.class)
+ public abstract static class StaticFieldMixin {
+ @JsonProperty("name")
+ static final String name = null;
+ }
+
+ @JsonMixin(target = SelectorMethodTarget.class)
+ public abstract static class ConcreteMethodMixin {
+ @JsonProperty("name")
+ public String getName() {
+ return "source";
+ }
+ }
+
+ @JsonMixin(target = BasicTarget.class)
+ @JsonType
+ public abstract static class JsonTypeMixin {}
+
+ @JsonMixin(target = BasicTarget.class)
+ @JsonMixinRemove(JsonType.class)
+ public abstract static class RemoveJsonTypeMixin {}
+
+ @JsonMixin(target = BasicTarget.class)
+ @JsonMixinRemove({})
+ public abstract static class EmptyRemoveMixin {}
+
+ @JsonMixin(target = BasicTarget.class)
+ @JsonMixinRemove({JsonProperty.class, JsonProperty.class})
+ public abstract static class DuplicateRemoveMixin {}
+
+ @JsonMixin(target = BasicTarget.class)
+ @JsonMixinRemove(Deprecated.class)
+ public abstract static class UnsupportedRemoveMixin {}
+
+ @JsonMixin(target = BasicTarget.class)
+ public abstract static class IllegalRemoveMixin {
+ @JsonMixinRemove(JsonPropertyOrder.class)
+ String name;
+ }
+
+ @JsonMixin(target = BasicTarget.class)
+ public abstract static class AddRemoveMixin {
+ @JsonProperty("name")
+ @JsonMixinRemove(JsonProperty.class)
+ String name;
+ }
+}
diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonTestSupport.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonTestSupport.java
index 515d43029..4ee6ec840 100644
--- a/java/fory-json/src/test/java/org/apache/fory/json/JsonTestSupport.java
+++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonTestSupport.java
@@ -20,6 +20,7 @@
package org.apache.fory.json;
import java.lang.reflect.Field;
+import java.util.Collections;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
import org.apache.fory.json.codec.JsonValueCodec;
@@ -47,6 +48,7 @@ final class JsonTestSupport {
1,
2 * 1024 * 1024,
new CodecRegistry(),
+ Collections.<Class<?>, Class<?>>emptyMap(),
null);
private static final JsonSharedRegistry REGISTRY = new JsonSharedRegistry(CONFIG);
private static final JsonValueCodec<Object> NULL_CODEC =
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@fory.apache.org
For additional commands, e-mail: commits-help@fory.apache.org