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/14 16:09:57 UTC
(fory) branch main updated: feat(java): add JSON codec annotation (#3844)
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 489e21080 feat(java): add JSON codec annotation (#3844)
489e21080 is described below
commit 489e21080f884d27eca792e203ae1120ae76c0be
Author: Shawn Yang <sh...@gmail.com>
AuthorDate: Tue Jul 14 21:39:53 2026 +0530
feat(java): add JSON codec annotation (#3844)
## 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/json-support.md | 267 +++++-
.../apache/fory/reflect/JvmTypeUseMetadata.java | 34 +
.../org/apache/fory/reflect/TypeUseMetadata.java | 45 +
.../apache/fory/reflect/TypeUseMetadataTest.java | 121 +++
java/fory-json/README.md | 298 ++++++-
.../main/java/org/apache/fory/json/ForyJson.java | 2 +-
.../java/org/apache/fory/json/ForyJsonBuilder.java | 4 +-
.../java/org/apache/fory/json/JsonTypeChecker.java | 8 +-
.../org/apache/fory/json/annotation/JsonCodec.java | 54 ++
.../org/apache/fory/json/codec/ArrayCodec.java | 12 +-
.../apache/fory/json/codec/ClosedSubtypeCodec.java | 2 +-
.../apache/fory/json/codec/CollectionCodec.java | 13 +-
.../org/apache/fory/json/codec/GuavaCodecs.java | 6 +-
.../codec/{JsonCodec.java => JsonValueCodec.java} | 17 +-
.../java/org/apache/fory/json/codec/MapCodec.java | 16 +-
.../org/apache/fory/json/codec/ObjectCodec.java | 33 +-
.../apache/fory/json/codec/ObjectCodecBuilder.java | 147 +++-
.../org/apache/fory/json/codec/ScalarCodecs.java | 146 ++--
.../org/apache/fory/json/codec/SqlJsonCodecs.java | 7 +-
.../org/apache/fory/json/codegen/JsonCodegen.java | 15 +
.../fory/json/meta/JsonCreatorFieldInfo.java | 8 +-
.../org/apache/fory/json/meta/JsonFieldInfo.java | 16 +-
.../org/apache/fory/json/meta/JsonTypeUse.java | 934 ++++++++++++++++++++
.../apache/fory/json/resolver/CodecRegistry.java | 20 +-
.../json/resolver/InheritedJsonValueCodec.java | 118 +++
.../fory/json/resolver/JsonCodecDeclaration.java | 52 ++
.../fory/json/resolver/JsonSharedRegistry.java | 360 +++++++-
.../apache/fory/json/resolver/JsonTypeInfo.java | 21 +-
.../fory/json/resolver/JsonTypeResolver.java | 396 +++++++--
.../apache/fory/json/JsonAsyncCompilationTest.java | 166 +++-
.../apache/fory/json/JsonCodecAnnotationTest.java | 970 +++++++++++++++++++++
.../apache/fory/json/JsonCodecHierarchyTest.java | 833 ++++++++++++++++++
.../java/org/apache/fory/json/JsonScalarTest.java | 12 +-
.../org/apache/fory/json/JsonSubTypesTest.java | 6 +-
.../java/org/apache/fory/json/JsonTestSupport.java | 18 +-
.../org/apache/fory/json/JsonTypeCheckerTest.java | 52 +-
.../org/apache/fory/json/meta/JsonTypeUseTest.java | 174 ++++
.../json/writer/Jdk25MultiReleaseJarVerifier.java | 2 +
.../module-codec-probe/closed/ClosedValue.java | 70 ++
.../resources/module-codec-probe/module-info.java | 1 +
.../module-codec-probe/opened/OpenedValue.java | 64 ++
.../resources/module-codec-probe/probe/Probe.java | 92 +-
42 files changed, 5364 insertions(+), 268 deletions(-)
diff --git a/docs/guide/java/json-support.md b/docs/guide/java/json-support.md
index c41c7f9ee..343ed46e8 100644
--- a/docs/guide/java/json-support.md
+++ b/docs/guide/java/json-support.md
@@ -20,8 +20,9 @@ license: |
---
Fory JSON is Apache Fory's thread-safe Java JSON codec. It supports Java objects, records,
-immutable creator-based classes, common JDK types, generic containers, exact custom codecs, and
-finite annotation-declared polymorphism through interpreted and runtime-generated codecs.
+immutable creator-based classes, common JDK types, generic containers, custom complete-value
+codecs, and finite annotation-declared polymorphism through interpreted and runtime-generated
+codecs.
Fory JSON is separate from Fory's binary native and xlang protocols. Use JSON for interoperable
text payloads such as HTTP APIs, browser traffic, logs, and configuration. Use the binary protocol
@@ -168,8 +169,8 @@ schema.
## Thread safety and code generation
-`ForyJson` is immutable and thread-safe after `build()`. Registered codecs and type checkers are
-shared and must also be thread-safe.
+`ForyJson` is immutable and thread-safe after `build()`. Registered and annotation-selected
+`JsonValueCodec` instances and type checkers are shared and must also be thread-safe.
Code generation and asynchronous compilation are enabled by default. Disable them for diagnostics
or environments that prohibit runtime compilation:
@@ -301,7 +302,7 @@ output size. Builder changes after `build()` do not mutate an existing runtime.
## Annotations
Fory JSON provides `JsonProperty`, `JsonPropertyOrder`, `JsonIgnore`, `JsonAnyProperty`,
-`JsonAnyGetter`, `JsonAnySetter`, `JsonCreator`, and `JsonSubTypes` under
+`JsonAnyGetter`, `JsonAnySetter`, `JsonCreator`, `JsonCodec`, and `JsonSubTypes` under
`org.apache.fory.json.annotation`. They are not Jackson, Gson, or Fory binary-protocol annotations.
```java
@@ -311,6 +312,7 @@ import org.apache.fory.json.PropertyNamingStrategy;
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.JsonCodec;
import org.apache.fory.json.annotation.JsonCreator;
import org.apache.fory.json.annotation.JsonIgnore;
import org.apache.fory.json.annotation.JsonProperty;
@@ -347,7 +349,7 @@ setter-only, creator-only, or write-ignored property is invalid.
Inclusion affects writing only. Identical repeated declarations are allowed; conflicting explicit
names, indexes, or non-default policies fail. Two properties cannot normalize to the same JSON
name. `JsonProperty` cannot be combined with an Any logical property or declared on a
-`JsonAnySetter`. `NON_EMPTY`, aliases, formatting, and annotation-selected codecs are unsupported.
+`JsonAnySetter`. `NON_EMPTY`, aliases, and formatting are unsupported.
### `JsonPropertyOrder`
@@ -623,25 +625,30 @@ public interface Shape {}
Wrapper inclusions support exact custom subtype codecs. Logical names and resolved concrete,
assignable classes must each be unique. Only exact listed runtime classes are accepted; listing a
parent does not admit descendants. The annotation is read from the declared base itself and is not
-inherited from another annotated base. Null is plain JSON null unless a custom codec on the
-declared base replaces the annotation. Readers accept only the configured shape, so changing
-inclusion is a wire-format change. At GraalVM native-image runtime, use class literals instead of
-`className`.
+inherited from another annotated base. Null is plain JSON null unless codec precedence selects a
+custom complete-value codec for the declared base, replacing the annotation. Readers accept only
+the configured shape, so changing inclusion is a wire-format change. At GraalVM native-image
+runtime, use class literals instead of `className`.
## Custom codecs
-An exact custom codec replaces the complete mapping for its registered class and owns null:
+`JsonValueCodec<T>` reads and writes one complete JSON value, including null, through Fory's
+concrete String/UTF-8 writers and Latin-1/UTF-16/UTF-8 readers. It is a direct streaming-value SPI,
+not a JSON abstract syntax tree (AST) codec. It never handles Map keys; `MapKeyCodec` owns JSON
+object member names.
+
+Implement all five representations with the same JSON shape:
```java
import java.math.BigDecimal;
-import org.apache.fory.json.codec.JsonCodec;
+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;
-public final class MoneyCodec implements JsonCodec<Money> {
+public final class MoneyCodec implements JsonValueCodec<Money> {
@Override
public void writeString(StringJsonWriter writer, Money value) {
if (value == null) {
@@ -696,10 +703,232 @@ ForyJson json =
.build();
```
-The parent property still controls its name, ignore direction, and inclusion before the codec runs.
-The codec instance is shared concurrently and must be thread-safe. A custom codec on a subtype is
-compatible with wrapper inclusion, not inline property inclusion. A codec on the base replaces its
-`JsonSubTypes` annotation.
+The parent property still controls its name, ignore direction, and null inclusion before the codec
+runs. An emitted property and every array, collection, map-value, Optional, or atomic-reference
+position delegate the complete value, including null. The registered codec instance is shared
+concurrently and must be thread-safe. A custom codec on a subtype is compatible with wrapper
+inclusion, not inline property inclusion. A codec on the base replaces its `JsonSubTypes`
+annotation.
+
+### `JsonCodec` declarations and type uses
+
+Use `@JsonCodec` on a class, record, enum, or interface to make a codec the default representation
+for that declaration and its descendants:
+
+```java
+@JsonCodec(MoneyCodec.class)
+public final class Money {}
+
+@JsonCodec(AccountCodec.class)
+public interface Account {}
+
+public final class RetailAccount implements Account {}
+```
+
+The default applies at root `Class` and raw `TypeRef` targets and at unannotated nested value
+positions. Fory explicitly inherits declarations through superclasses and interfaces; it does not
+use Java `@Inherited`.
+
+Use the same annotation at a type-use position to select a codec for exactly that occurrence:
+
+```java
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+public final class Invoice {
+ public @JsonCodec(MoneyCodec.class) Money total;
+ public List<@JsonCodec(MoneyCodec.class) Money> items;
+ public Set<@JsonCodec(MoneyCodec.class) Money> uniqueItems;
+ public Collection<@JsonCodec(MoneyCodec.class) Money> allItems;
+ public Map<String, @JsonCodec(MoneyCodec.class) Money> byName;
+ public Optional<@JsonCodec(MoneyCodec.class) Money> optional;
+ public AtomicReference<@JsonCodec(MoneyCodec.class) Money> current;
+
+ // Codec for each element.
+ public @JsonCodec(MoneyCodec.class) Money[] itemArray;
+
+ // Codec for the complete array value.
+ public Money @JsonCodec(MoneyArrayCodec.class) [] encodedArray;
+
+ // Codec for each complete inner Set value.
+ public List<@JsonCodec(MoneySetCodec.class) Set<Money>> groups;
+
+ // Normal containers with a codec only at the leaf.
+ public List<Set<@JsonCodec(MoneyCodec.class) Money>> nestedItems;
+}
+```
+
+Every array dimension is a distinct type-use node. This recursive model also covers
+multidimensional arrays, `AtomicReferenceArray`, concrete containers, and generic container
+subclasses. Fory follows the inherited `Collection<E>` or `Map<K,V>` binding instead of assuming a
+fixed type-argument index.
+
+One logical property's field, effective getter, effective setter, record component, and matching
+creator parameter contribute to one resolved codec tree. Missing annotations are not conflicts;
+equal codec classes at one node merge, while different classes fail with both sources and the
+nested path. Type-use metadata survives generic substitution, including a codec attached to a
+bound type argument used by a field declared as a type variable. Supported positions include field
+and record-component types, getter return types, setter value parameters, and `JsonCreator`
+constructor or factory value parameters.
+
+`TypeRef` preserves ordinary Java generic types but not arbitrary occurrence annotations. A root
+`TypeRef<List<@JsonCodec(...) Money>>` therefore cannot carry that local override. Put it on a
+discovered model property, declare a default on `Money`, or use exact builder registration.
+
+### Codec precedence
+
+Fory chooses the complete codec for each current resolved value node using this exact order. An
+invalid higher-priority source fails rather than falling back.
+
+| Priority | Source | Matching rule |
+| -------: | --------------------------------------- | ------------------------------------------------------------------------- |
+| 1 | Current `TYPE_USE @JsonCodec` | Exact resolved occurrence after property merging and generic substitution |
+| 2 | `registerCodec(Target.class, instance)` | Exact target `Class`; never inherited |
+| 3 | Direct `@JsonCodec` declaration | Current class, record, enum, or interface |
+| 4 | Inherited `@JsonCodec` declaration | Most-specific superclass/interface result |
+| 5 | Existing mapping | `JsonSubTypes`, built-in/container mapping, then default object mapping |
+
+Rows 1 through 4 replace the whole current value mapping. They may therefore replace a scalar,
+enum, container, object, or `JsonSubTypes` representation. A current type-use, exact registration,
+or direct declaration also resolves any lower-priority inherited ambiguity.
+
+### Deterministic inheritance and conflicts
+
+For inherited declarations, Fory collects every annotated proper superclass and interface, then
+removes a candidate when another declaring type is its Java subtype. The remaining most-specific
+declarations resolve as follows:
+
+- one declaration wins;
+- unrelated declarations naming the same codec class are consistent;
+- unrelated declarations naming different codec classes conflict.
+
+This is independent of `implements` order and reflection order. A child interface declaration
+overrides its parent declaration, and a child class declaration overrides its parent:
+
+```java
+@JsonCodec(ParentCodec.class)
+interface Parent {}
+
+@JsonCodec(ChildCodec.class)
+interface Child extends Parent {}
+
+final class Value implements Child {} // ChildCodec
+
+@JsonCodec(BaseCodec.class)
+class Base {}
+
+@JsonCodec(ValueCodec.class)
+final class Concrete extends Base {} // ValueCodec
+```
+
+Unrelated interfaces using a common codec are valid; different codecs are ambiguous:
+
+```java
+@JsonCodec(CommonCodec.class)
+interface A {}
+
+@JsonCodec(CommonCodec.class)
+interface B {}
+
+final class Consistent implements A, B {}
+
+@JsonCodec(ACodec.class)
+interface Left {}
+
+@JsonCodec(BCodec.class)
+interface Right {}
+
+final class Ambiguous implements Left, Right {} // Metadata error.
+```
+
+Superclass/interface candidates follow the same subtype rule:
+
+| Declaring-type relationship | Codec classes | Result |
+| ----------------------------------------------- | ----------------- | --------------------------------------------------------- |
+| Superclass implements or inherits the interface | Same or different | Superclass declaration wins because it is more specific |
+| Superclass and interface are unrelated | Same | Common codec is accepted |
+| Superclass and interface are unrelated | Different | Conflict; class does not automatically override interface |
+
+Disambiguate by annotating the concrete class, annotating only the current type use, or registering
+an exact codec instance:
+
+```java
+@JsonCodec(ConcreteCodec.class)
+final class DeclaredValue implements Left, Right {}
+
+final class Holder {
+ public @JsonCodec(LocalCodec.class) Ambiguous value;
+}
+
+ForyJson json =
+ ForyJson.builder()
+ .registerCodec(Ambiguous.class, new ConcreteCodec())
+ .build();
+```
+
+Fory retains Jackson's useful idea of explicitly inheriting annotations through class and
+interface hierarchies, but rejects traversal-order first-wins behavior. Java subtype specificity
+and codec-class identity decide the result; incomparable different codecs produce an error instead
+of depending on hierarchy declaration order.
+
+### Nested composition and Map keys
+
+A custom codec owns its complete current value and cannot delegate annotated children. An explicit
+nested type-use under an outer custom codec is therefore rejected as hidden configuration:
+
+```java
+// Invalid: LocalCodec cannot run because CustomListCodec owns the whole list.
+public @JsonCodec(CustomListCodec.class)
+ List<@JsonCodec(LocalCodec.class) Money> values;
+```
+
+A child class's declaration codec is only a lazy default. The outer codec prevents child lookup,
+so that default is not a hidden explicit instruction and is valid:
+
+```java
+@JsonCodec(MoneyCodec.class)
+final class DeclaredMoney {}
+
+public @JsonCodec(CustomListCodec.class) List<DeclaredMoney> values;
+```
+
+The hidden-explicit-descendant rule also applies when the outer complete codec comes from builder
+registration or a class/interface declaration. Without an outer custom codec, arrays, collections,
+map values, Optional, and atomic references resolve their annotated children normally.
+
+Map keys are JSON object member names, not JSON values. An explicit `@JsonCodec` anywhere in a Map
+key subtree is rejected. Builder or declaration value codecs on the key's raw type are ignored in
+key position and still apply when that type is used as a value. For `JsonAnyProperty`,
+`JsonAnyGetter`, and `JsonAnySetter`, the outer Map is flattened and cannot select a whole-value
+codec; only its value node can. Wildcards, wildcard bounds, and type variables still unresolved
+after substitution cannot select a codec. A type-use on an `extends` or `implements` clause is not
+a JSON value occurrence and is not used; annotate the type declaration instead. Annotation type
+declarations are not supported JSON model targets.
+
+### Construction, inherited results, and platform support
+
+An annotation codec class must be public, concrete, top-level or static nested, and have a public
+no-argument constructor. One successfully constructed instance is shared by all annotated sites
+and concurrent operations of the built `ForyJson`; it must be thread-safe. Use
+`registerCodec(Target.class, instance)` when the codec needs configuration.
+
+In a named Java module, export or open the codec's package to `org.apache.fory.json`. Fory does not
+bypass a closed module boundary and reports an actionable access error.
+
+When a parent or interface declaration supplies the codec for a more specific target, every reader
+result must be null or assignable to that target. A parent codec may return the requested child and
+succeed. Returning a plain parent while decoding the child fails with `ForyJsonException` that
+names the target type, codec class, declaring type, and actual returned type. The actual result,
+not the parent's `final` status or the codec's generic signature, determines validity.
+
+`@JsonCodec` is supported on ordinary JVMs. Android and GraalVM native image ignore both declaration
+and type-use forms, avoiding partial behavior when nested runtime type metadata is unavailable. Use
+exact `registerCodec` registration there. Native-image reflection configuration is not a supported
+way to enable part of this annotation feature.
## Type validation and untrusted input
@@ -718,7 +947,8 @@ ForyJson json =
Allow every application model and non-built-in container type that the declared schema uses. The
checker applies while application types are prepared for serialization and parsing and must be
-thread-safe. Built-in scalars normally skip the custom checker. Custom codecs cannot bypass the
+thread-safe. Built-in scalars normally skip the custom checker, but selecting an application codec
+for a built-in target makes that target subject to the checker. Custom codecs cannot bypass the
fixed disallow list.
`withClassLoader` fixes subtype `className` resolution. Otherwise `build()` snapshots the thread
@@ -753,6 +983,7 @@ Circular graphs eventually fail `maxDepth`; they are not reconstructed.
| Ordinary object cannot be created | Add a usable no-argument constructor, use a record or creator, or register a codec |
| Ordinary accessor annotation fails | Use an eligible public JavaBean accessor and disable field mode |
| Any annotation fails | Use one field form or one valid method pair with resolved `Map<String, V>` types |
+| Codec annotation fails | Resolve same-node or hierarchy conflicts, hidden nested overrides, or codec constructor access |
| Subtype fails | Write with the declared base, list the exact runtime class, and use the configured wire shape |
| Collection fails | Target a supported interface/common implementation or register a codec |
diff --git a/java/fory-core/src/main/java/org/apache/fory/reflect/JvmTypeUseMetadata.java b/java/fory-core/src/main/java/org/apache/fory/reflect/JvmTypeUseMetadata.java
index 60fea96fe..37ac02561 100644
--- a/java/fory-core/src/main/java/org/apache/fory/reflect/JvmTypeUseMetadata.java
+++ b/java/fory-core/src/main/java/org/apache/fory/reflect/JvmTypeUseMetadata.java
@@ -23,6 +23,8 @@ import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedArrayType;
import java.lang.reflect.AnnotatedParameterizedType;
import java.lang.reflect.AnnotatedType;
+import java.lang.reflect.AnnotatedWildcardType;
+import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
@@ -145,6 +147,11 @@ final class JvmTypeUseMetadata implements TypeUseMetadata.Support {
return method.getAnnotatedParameterTypes();
}
+ @Override
+ public Object[] constructorParameterTypeUses(Constructor<?> constructor) {
+ return constructor.getAnnotatedParameterTypes();
+ }
+
@Override
public Object recordComponentTypeUse(RecordComponent component) {
return component.getTypeUseMetadata();
@@ -159,6 +166,33 @@ final class JvmTypeUseMetadata implements TypeUseMetadata.Support {
return null;
}
+ @Override
+ public Object arrayComponentTypeUse(Object typeUse) {
+ AnnotatedType annotatedType = (AnnotatedType) typeUse;
+ if (annotatedType instanceof AnnotatedArrayType) {
+ return ((AnnotatedArrayType) annotatedType).getAnnotatedGenericComponentType();
+ }
+ return null;
+ }
+
+ @Override
+ public Object[] wildcardUpperBounds(Object typeUse) {
+ AnnotatedType annotatedType = (AnnotatedType) typeUse;
+ if (annotatedType instanceof AnnotatedWildcardType) {
+ return ((AnnotatedWildcardType) annotatedType).getAnnotatedUpperBounds();
+ }
+ return null;
+ }
+
+ @Override
+ public Object[] wildcardLowerBounds(Object typeUse) {
+ AnnotatedType annotatedType = (AnnotatedType) typeUse;
+ if (annotatedType instanceof AnnotatedWildcardType) {
+ return ((AnnotatedWildcardType) annotatedType).getAnnotatedLowerBounds();
+ }
+ return null;
+ }
+
@Override
public Annotation typeUseAnnotation(Object typeUse, String name) {
return getTypeUseAnnotation((AnnotatedType) typeUse, name);
diff --git a/java/fory-core/src/main/java/org/apache/fory/reflect/TypeUseMetadata.java b/java/fory-core/src/main/java/org/apache/fory/reflect/TypeUseMetadata.java
index 02b0bf97e..26a972e79 100644
--- a/java/fory-core/src/main/java/org/apache/fory/reflect/TypeUseMetadata.java
+++ b/java/fory-core/src/main/java/org/apache/fory/reflect/TypeUseMetadata.java
@@ -20,6 +20,7 @@
package org.apache.fory.reflect;
import java.lang.annotation.Annotation;
+import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.apache.fory.annotation.Internal;
@@ -54,6 +55,10 @@ public final class TypeUseMetadata {
return SUPPORT.methodParameterTypeUses(method);
}
+ public static Object[] constructorParameterTypeUses(Constructor<?> constructor) {
+ return SUPPORT.constructorParameterTypeUses(constructor);
+ }
+
public static Object recordComponentTypeUse(RecordComponent component) {
return SUPPORT.recordComponentTypeUse(component);
}
@@ -62,6 +67,18 @@ public final class TypeUseMetadata {
return SUPPORT.typeUseArguments(typeUse);
}
+ public static Object arrayComponentTypeUse(Object typeUse) {
+ return SUPPORT.arrayComponentTypeUse(typeUse);
+ }
+
+ public static Object[] wildcardUpperBounds(Object typeUse) {
+ return SUPPORT.wildcardUpperBounds(typeUse);
+ }
+
+ public static Object[] wildcardLowerBounds(Object typeUse) {
+ return SUPPORT.wildcardLowerBounds(typeUse);
+ }
+
public static Annotation typeUseAnnotation(Object typeUse, String name) {
return SUPPORT.typeUseAnnotation(typeUse, name);
}
@@ -98,10 +115,18 @@ public final class TypeUseMetadata {
Object[] methodParameterTypeUses(Method method);
+ Object[] constructorParameterTypeUses(Constructor<?> constructor);
+
Object recordComponentTypeUse(RecordComponent component);
Object[] typeUseArguments(Object typeUse);
+ Object arrayComponentTypeUse(Object typeUse);
+
+ Object[] wildcardUpperBounds(Object typeUse);
+
+ Object[] wildcardLowerBounds(Object typeUse);
+
Annotation typeUseAnnotation(Object typeUse, String name);
<A extends Annotation> A typeUseAnnotation(Object typeUse, Class<A> annotationClass);
@@ -131,6 +156,11 @@ public final class TypeUseMetadata {
return null;
}
+ @Override
+ public Object[] constructorParameterTypeUses(Constructor<?> constructor) {
+ return null;
+ }
+
@Override
public Object recordComponentTypeUse(RecordComponent component) {
return null;
@@ -141,6 +171,21 @@ public final class TypeUseMetadata {
return null;
}
+ @Override
+ public Object arrayComponentTypeUse(Object typeUse) {
+ return null;
+ }
+
+ @Override
+ public Object[] wildcardUpperBounds(Object typeUse) {
+ return null;
+ }
+
+ @Override
+ public Object[] wildcardLowerBounds(Object typeUse) {
+ return null;
+ }
+
@Override
public Annotation typeUseAnnotation(Object typeUse, String name) {
return null;
diff --git a/java/fory-core/src/test/java/org/apache/fory/reflect/TypeUseMetadataTest.java b/java/fory-core/src/test/java/org/apache/fory/reflect/TypeUseMetadataTest.java
new file mode 100644
index 000000000..d583b962a
--- /dev/null
+++ b/java/fory-core/src/test/java/org/apache/fory/reflect/TypeUseMetadataTest.java
@@ -0,0 +1,121 @@
+/*
+ * 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.reflect;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertNull;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.util.List;
+import org.apache.fory.platform.JdkVersion;
+import org.testng.annotations.Test;
+
+public class TypeUseMetadataTest {
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target(ElementType.TYPE_USE)
+ private @interface Marker {
+ String value();
+ }
+
+ private static class TypeUses {
+ @Marker("element")
+ String[] elementAnnotated;
+
+ String @Marker("array") [] arrayAnnotated;
+ List<@Marker("wildcard") ? extends @Marker("upper") Number> upperBound;
+ List<? super @Marker("lower") Integer> lowerBound;
+
+ TypeUses(List<@Marker("parameter") String> values) {}
+ }
+
+ @Test
+ public void testArrayComponentTypeUse() throws Exception {
+ Object elementArray = fieldTypeUse("elementAnnotated");
+ assertNull(TypeUseMetadata.typeUseAnnotation(elementArray, Marker.class));
+ assertMarker(TypeUseMetadata.arrayComponentTypeUse(elementArray), "element");
+
+ Object annotatedArray = fieldTypeUse("arrayAnnotated");
+ assertMarker(annotatedArray, "array");
+ Object component = TypeUseMetadata.arrayComponentTypeUse(annotatedArray);
+ assertNotNull(component);
+ assertNull(TypeUseMetadata.typeUseAnnotation(component, Marker.class));
+
+ assertNull(TypeUseMetadata.arrayComponentTypeUse(component));
+ }
+
+ @Test
+ public void testConstructorParameterTypeUses() throws Exception {
+ Constructor<?> constructor = TypeUses.class.getDeclaredConstructor(List.class);
+ Object[] parameters = TypeUseMetadata.constructorParameterTypeUses(constructor);
+ assertEquals(parameters.length, 1);
+ Object[] arguments = TypeUseMetadata.typeUseArguments(parameters[0]);
+ assertEquals(arguments.length, 1);
+ assertMarker(arguments[0], "parameter");
+ }
+
+ @Test
+ public void testWildcardBounds() throws Exception {
+ Object upperWildcard = onlyTypeArgument("upperBound");
+ assertMarker(upperWildcard, "wildcard");
+ Object[] upperBounds = TypeUseMetadata.wildcardUpperBounds(upperWildcard);
+ assertEquals(upperBounds.length, 1);
+ assertMarker(upperBounds[0], "upper");
+ assertEquals(TypeUseMetadata.wildcardLowerBounds(upperWildcard).length, 0);
+
+ Object lowerWildcard = onlyTypeArgument("lowerBound");
+ Object[] lowerBounds = TypeUseMetadata.wildcardLowerBounds(lowerWildcard);
+ assertEquals(lowerBounds.length, 1);
+ assertMarker(lowerBounds[0], "lower");
+ Object[] implicitUpperBounds = TypeUseMetadata.wildcardUpperBounds(lowerWildcard);
+ if (JdkVersion.MAJOR_VERSION == 8) {
+ // JDK 8 omits the implicit Object upper bound for ? super T.
+ assertEquals(implicitUpperBounds.length, 0);
+ } else {
+ assertEquals(implicitUpperBounds.length, 1);
+ assertEquals(TypeUseMetadata.typeRef(implicitUpperBounds[0]).getRawType(), Object.class);
+ }
+
+ assertNull(TypeUseMetadata.wildcardUpperBounds(lowerBounds[0]));
+ assertNull(TypeUseMetadata.wildcardLowerBounds(lowerBounds[0]));
+ }
+
+ private static Object fieldTypeUse(String name) throws Exception {
+ Field field = TypeUses.class.getDeclaredField(name);
+ return TypeUseMetadata.fieldTypeUse(field);
+ }
+
+ private static Object onlyTypeArgument(String fieldName) throws Exception {
+ Object[] arguments = TypeUseMetadata.typeUseArguments(fieldTypeUse(fieldName));
+ assertEquals(arguments.length, 1);
+ return arguments[0];
+ }
+
+ private static void assertMarker(Object typeUse, String value) {
+ Marker marker = TypeUseMetadata.typeUseAnnotation(typeUse, Marker.class);
+ assertNotNull(marker);
+ assertEquals(marker.value(), value);
+ }
+}
diff --git a/java/fory-json/README.md b/java/fory-json/README.md
index 93a6b5050..9f19704be 100644
--- a/java/fory-json/README.md
+++ b/java/fory-json/README.md
@@ -2,7 +2,8 @@
Fory JSON is Apache Fory's thread-safe Java JSON codec. It provides interpreted and
runtime-generated codecs for Java objects, records, immutable creator-based classes, common JDK
-types, generic containers, exact custom codecs, and finite annotation-declared polymorphism.
+types, generic containers, custom complete-value codecs, and finite annotation-declared
+polymorphism.
Fory JSON is a separate data format from Fory's binary native and xlang protocols. Use it when a
system must exchange ordinary JSON with browsers, APIs, logs, configuration, or another JSON
@@ -167,8 +168,8 @@ String encoded = json.toJson(shapes, shapesType);
## Thread safety, reuse, and code generation
`ForyJson` is immutable and thread-safe after `build()`. Reuse one instance instead of creating a
-builder and runtime for every operation. A registered `JsonCodec` and `JsonTypeChecker` may be
-called concurrently and must also be thread-safe.
+builder and runtime for every operation. Registered and annotation-selected `JsonValueCodec`
+instances and the `JsonTypeChecker` may be called concurrently and must also be thread-safe.
Code generation and asynchronous compilation are enabled by default. Disabling code generation is
useful for diagnostics or environments that prohibit runtime compilation:
@@ -357,8 +358,9 @@ Builder mutation after `build()` does not modify an existing `ForyJson` runtime.
## JSON annotations
-Fory JSON defines eight annotations in `org.apache.fory.json.annotation`. They are Fory JSON APIs,
-not Jackson, Gson, or Fory binary-protocol compatibility annotations.
+Fory JSON defines nine annotations in `org.apache.fory.json.annotation`, including `JsonCodec` for
+complete-value codec selection. They are Fory JSON APIs, not Jackson, Gson, or Fory binary-protocol
+compatibility annotations.
### `JsonProperty`
@@ -405,9 +407,8 @@ order before unindexed properties. Indexes must be non-negative, may contain gap
unique among writable properties. `-1` means unspecified; lower values are invalid. An index on a
setter-only, creator-only, or write-ignored property is invalid.
-`NON_EMPTY`, aliases, formatting, annotation-selected codecs, and independent read/write names are
-not supported. `JsonProperty` cannot be combined with an Any logical property or declared on a
-`JsonAnySetter`.
+`NON_EMPTY`, aliases, formatting, and independent read/write names are not supported.
+`JsonProperty` cannot be combined with an Any logical property or declared on a `JsonAnySetter`.
### `JsonPropertyOrder`
@@ -734,8 +735,8 @@ The configuration rules are strict:
| `WRAPPER_ARRAY` | Must be empty | Complete subtype value as array element 1 |
Both wrappers may delegate to an exact custom subtype codec. All three inclusions write null as
-plain JSON null unless an exact custom codec registered for the declared base replaces the
-annotation.
+plain JSON null unless codec precedence selects a custom complete-value codec for the declared
+base, replacing the annotation.
The base must be an interface or abstract class. Every entry must resolve to a unique concrete,
assignable class, and serialization accepts only an exact listed runtime class. Listing a parent
@@ -748,23 +749,24 @@ At GraalVM native-image runtime, use class-literal entries rather than `classNam
## Custom codecs
-Register a custom `JsonCodec<T>` when a class needs a representation that is not provided by the
-built-in mapping. Registration is exact-class only and replaces the built-in, object, or subtype
-annotation codec for that class.
+`JsonValueCodec<T>` is Fory JSON's streaming codec SPI for one complete JSON value. It writes
+directly to Fory's String or UTF-8 writer and reads directly from Fory's Latin-1, UTF-16, or UTF-8
+reader. It is not a JSON abstract syntax tree (AST) or `JsonNode` codec. It owns the complete value,
+including JSON null, but never handles a Map key; `MapKeyCodec` remains responsible for JSON object
+member names.
-A codec implements both output representations and all three input representations. It owns one
-complete value, including its null behavior:
+Implement all five representations with the same JSON shape:
```java
import java.math.BigDecimal;
-import org.apache.fory.json.codec.JsonCodec;
+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;
-public final class MoneyCodec implements JsonCodec<Money> {
+public final class MoneyCodec implements JsonValueCodec<Money> {
@Override
public void writeString(StringJsonWriter writer, Money value) {
if (value == null) {
@@ -817,15 +819,263 @@ ForyJson json =
.build();
```
-The parent object's property name, ignore direction, and inclusion policy are applied before the
-selected value codec runs. An omitted null property does not call its codec; a selected property
-does. The same codec instance is shared across concurrent operations, so implementations must be
-thread-safe.
+The containing property still controls its name, ignore direction, and null-inclusion policy. If a
+null property is omitted, the value codec is not called. If the property is emitted, or the value
+is an array element, collection element, map value, Optional value, or atomic-reference value, the
+codec receives and owns null. The registered instance is shared across concurrent operations and
+must be thread-safe.
Registering a custom codec for a `JsonSubTypes` base replaces that base's subtype annotation.
Registering one for a listed subtype is supported by the two wrapper inclusions but not by inline
property inclusion.
+### Selecting a codec with `JsonCodec`
+
+Use `@JsonCodec` on a class, record, enum, or interface to declare its default JSON representation:
+
+```java
+import org.apache.fory.json.annotation.JsonCodec;
+
+@JsonCodec(MoneyCodec.class)
+public final class Money {
+ // ...
+}
+
+@JsonCodec(AccountCodec.class)
+public interface Account {}
+
+public final class RetailAccount implements Account {}
+```
+
+The declaration applies at the root and at unannotated nested value positions. It is inherited
+through both superclasses and interfaces, so `RetailAccount` uses `AccountCodec` unless a
+higher-priority choice overrides it. Records and enums use the same declaration form. Fory does
+not rely on Java `@Inherited`, which does not cover interfaces.
+
+Use `@JsonCodec` at a type-use position to change one exact occurrence while retaining the normal
+mapping around it:
+
+```java
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+public final class Invoice {
+ public @JsonCodec(MoneyCodec.class) Money total;
+
+ public List<@JsonCodec(MoneyCodec.class) Money> items;
+ public Set<@JsonCodec(MoneyCodec.class) Money> uniqueItems;
+ public Collection<@JsonCodec(MoneyCodec.class) Money> allItems;
+ public Map<String, @JsonCodec(MoneyCodec.class) Money> byName;
+ public Optional<@JsonCodec(MoneyCodec.class) Money> optional;
+ public AtomicReference<@JsonCodec(MoneyCodec.class) Money> current;
+
+ // Codec for each Money element.
+ public @JsonCodec(MoneyCodec.class) Money[] itemArray;
+
+ // Codec for the complete Money[] value.
+ public Money @JsonCodec(MoneyArrayCodec.class) [] encodedArray;
+
+ // Codec for each complete inner Set<Money> value.
+ public List<@JsonCodec(MoneySetCodec.class) Set<Money>> groups;
+
+ // Normal containers with a codec only at the leaf.
+ public List<Set<@JsonCodec(MoneyCodec.class) Money>> nestedItems;
+}
+```
+
+Every array dimension is a separate type-use node. The same recursive model applies to
+multidimensional arrays, `AtomicReferenceArray`, concrete collection and map implementations, and
+generic container subclasses. Fory follows the actual inherited `Collection<E>` or `Map<K,V>`
+binding, so reordered type parameters still select the intended element or value.
+
+For a logical property, annotations from its field, effective getter, effective setter, record
+component, and matching creator parameter are merged after generic substitution. Missing
+annotations are not conflicts. Repeating the same codec at the same resolved node is allowed;
+different codec classes at that node fail metadata construction and identify both sources and the
+nested type path. An annotation on a bound type argument is preserved through fields declared with
+that type variable. The type-use form is supported on field and record-component types, getter
+return types, setter value parameters, and `JsonCreator` constructor or factory value parameters.
+
+Root APIs that accept a `Class` or a Fory `TypeRef` apply class/interface declaration defaults.
+Java `TypeRef` does not preserve arbitrary occurrence annotations, so a root
+`TypeRef<List<@JsonCodec(...) Money>>` cannot provide that nested override. Put the type-use on a
+discovered model property, declare the default on `Money`, or use exact builder registration.
+
+### Selection precedence
+
+For the current resolved value node and target class, the first applicable row wins. An invalid
+higher-priority configuration fails instead of falling back.
+
+| Priority | Source | Match |
+| -------: | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
+| 1 | Current `TYPE_USE @JsonCodec` | This exact resolved occurrence after property merging and generic substitution |
+| 2 | `registerCodec(Target.class, instance)` | Exact target `Class`; registrations are not inherited |
+| 3 | `@JsonCodec` declared directly on the current class, record, enum, or interface | Exact current declaration |
+| 4 | Inherited class/interface `@JsonCodec` | Deterministic most-specific declaration described below |
+| 5 | Existing mapping | `JsonSubTypes`, built-in/container mapping, then default object mapping |
+
+Any choice in rows 1 through 4 replaces the complete value mapping, including a built-in,
+container, enum, `JsonSubTypes`, or object mapping. A current type-use, exact builder registration,
+or direct declaration also resolves an otherwise ambiguous inherited configuration without
+evaluating that lower-priority conflict.
+
+Builder registration is exact-class only and remains the path for configured codec instances.
+Registering a codec for a parent or interface does not apply it to descendants.
+
+### Deterministic declaration inheritance
+
+When only inherited declarations remain, Fory considers all annotated proper superclasses and
+interfaces. A declaration is discarded when another candidate declaration is on its Java subtype.
+The remaining most-specific declarations determine the result:
+
+- one candidate wins;
+- multiple candidates naming the same codec class are consistent;
+- incomparable candidates naming different codec classes are an error.
+
+This result never depends on `implements` order or reflection traversal order. A child interface
+declaration overrides its annotated parent, and a child class declaration overrides its annotated
+parent. For superclass/interface combinations:
+
+| Relationship between declaring types | Codec classes | Result |
+| ----------------------------------------------- | ----------------- | ---------------------------------------------------------- |
+| Superclass implements or inherits the interface | Same or different | The superclass declaration is more specific |
+| Superclass and interface are unrelated | Same | Consistent; use the common codec |
+| Superclass and interface are unrelated | Different | Conflict; a class does not automatically beat an interface |
+
+For example, unrelated interfaces using the same codec are valid, while different codecs conflict:
+
+```java
+@JsonCodec(CommonCodec.class)
+interface A {}
+
+@JsonCodec(CommonCodec.class)
+interface B {}
+
+final class ConsistentValue implements A, B {}
+
+@JsonCodec(ACodec.class)
+interface Left {}
+
+@JsonCodec(BCodec.class)
+interface Right {}
+
+// Resolving this type reports both declarations, in stable order.
+final class AmbiguousValue implements Left, Right {}
+```
+
+A child interface or class is more specific than its annotated ancestor:
+
+```java
+@JsonCodec(ParentCodec.class)
+interface Parent {}
+
+@JsonCodec(ChildCodec.class)
+interface Child extends Parent {}
+
+final class ChildValue implements Child {} // ChildCodec
+
+@JsonCodec(BaseCodec.class)
+class Base {}
+
+@JsonCodec(ConcreteCodec.class)
+final class Concrete extends Base {} // ConcreteCodec
+```
+
+Resolve an inherited conflict explicitly in any of three ways:
+
+```java
+// Type-wide declaration for this concrete class.
+@JsonCodec(ConcreteCodec.class)
+final class DeclaredValue implements Left, Right {}
+
+final class Holder {
+ // Only this occurrence.
+ public @JsonCodec(LocalCodec.class) AmbiguousValue value;
+}
+
+// Exact type-wide instance, including configured codecs.
+ForyJson json =
+ ForyJson.builder()
+ .registerCodec(AmbiguousValue.class, new ConcreteCodec())
+ .build();
+```
+
+Like Jackson, Fory preserves useful annotation inheritance across classes and interfaces by
+traversing the Java hierarchy itself. Unlike Jackson's traversal-order first-wins merge, Fory uses
+Java subtype specificity, accepts equal codec classes, and rejects incomparable different codecs.
+Changing `implements` order therefore cannot silently change the JSON representation.
+
+### Composition rules
+
+A selected custom codec owns its entire current value and has no child-delegation API. If source
+code also places an explicit `TYPE_USE @JsonCodec` below that node, metadata construction fails
+because the nested instruction would be hidden, even when it names the same codec:
+
+```java
+public final class Holder {
+ // Invalid: CustomListCodec owns the list, so LocalCodec could never run.
+ public @JsonCodec(CustomListCodec.class)
+ List<@JsonCodec(LocalCodec.class) Money> values;
+}
+```
+
+A child type's declaration annotation is different: it is a lazy default rather than an explicit
+instruction at this occurrence. An outer complete codec intentionally prevents that default from
+being resolved, so this is valid:
+
+```java
+@JsonCodec(MoneyCodec.class)
+final class DeclaredMoney {}
+
+public final class Holder {
+ public @JsonCodec(CustomListCodec.class) List<DeclaredMoney> values;
+}
+```
+
+The same hidden-explicit-descendant rule applies when the outer codec comes from exact builder
+registration or a type declaration. Without an outer custom codec, normal array, collection,
+map-value, Optional, and atomic-reference codecs resolve their annotated children normally.
+
+`@JsonCodec` is a value-codec annotation. An explicit occurrence anywhere in a Map key subtree is
+rejected; declaration defaults and builder registrations for a key type are ignored in key
+position. They still apply when that type appears as a JSON value. For `JsonAnyProperty`,
+`JsonAnyGetter`, or `JsonAnySetter`, only the Map value may select a value codec because the outer
+Map is flattened into its containing object. Wildcard nodes, wildcard bounds, and type variables
+that remain unresolved after substitution cannot select a codec. A type-use written on an
+`extends` or `implements` clause is a hierarchy path rather than a JSON value occurrence and is not
+used; put the annotation on the type declaration instead. Annotation type declarations are not
+supported JSON model targets.
+
+### Construction, inherited results, and platforms
+
+An annotation names a codec class rather than an instance. The class must be public, concrete,
+top-level or static nested, and have a public no-argument constructor. Fory constructs one instance
+per codec implementation class and built `ForyJson`, then shares it across every annotated site and
+concurrent caller. Implementations must be thread-safe. Constructor failures are not cached as
+successful instances; a codec requiring configuration should be passed as an instance through
+`registerCodec`.
+
+In a named Java module, the codec package must be exported or opened to `org.apache.fory.json` so
+the public constructor is accessible. Fory respects closed module boundaries and reports the codec
+class, package, and target module when access is unavailable.
+
+An inherited parent or interface codec may be subtype-aware. When it is used for a more specific
+target, each reader result must be null or assignable to that current target. For example, a codec
+declared on non-final `Base` may return a `Child` while decoding `Child`; that succeeds. Returning a
+plain `Base` fails with `ForyJsonException` containing the target type, codec class, declaring type,
+and actual returned class. Fory validates the actual result rather than rejecting inheritance based
+on the codec's generic signature.
+
+`@JsonCodec` declaration and type-use discovery is supported on ordinary JVMs. Android and GraalVM
+native image ignore all `@JsonCodec` sources so that declaration defaults cannot work while nested
+type-use metadata silently disappears. Use exact `registerCodec(Target.class, instance)`
+registration for both environments. Native-image reflection configuration is not a supported way
+to enable only part of the annotation feature.
+
## Type validation and untrusted input
Fory JSON never derives a Java class name from JSON input. It always applies Fory's fixed disallow
@@ -845,8 +1095,9 @@ ForyJson json =
Allow every application model and non-built-in container type that the declared schema uses. The
checker is used while application types are prepared for both serialization and parsing and must be
-thread-safe. Built-in scalar types normally do not invoke the custom checker. A custom codec does
-not bypass Fory's fixed disallow list.
+thread-safe. Built-in scalar types normally do not invoke the custom checker, but selecting an
+application codec for a built-in target makes that target subject to the checker. A custom codec
+does not bypass Fory's fixed disallow list.
`withClassLoader` sets the fixed loader for annotation-declared subtype `className` entries. If it
is not configured, `build()` snapshots the current thread context class loader and falls back to the
@@ -890,6 +1141,7 @@ native or xlang protocol when reference identity or cycles are required.
| Ordinary object cannot be constructed | Add a usable no-argument constructor, use a record or `JsonCreator`, or register a custom codec; Android and GraalVM native image are stricter |
| Ordinary accessor annotation fails | The method is not an eligible public JavaBean accessor, or field mode is enabled |
| Any annotation fails | Use exactly one field-backed form or one valid method-backed pair with resolved `Map<String, V>` types; method annotations require non-field mode |
+| Codec annotation fails | Resolve same-node or hierarchy conflicts, remove a hidden nested override, or use a public no-argument codec class |
| Subtype is rejected | The base is not declared on the write, the runtime class is not an exact table entry, or the input wire shape differs from the configured inclusion |
| Collection cannot be read | Target a supported interface/common implementation or register a custom codec |
| OutputStream write fails | The underlying `IOException` is wrapped as the cause of `ForyJsonException` |
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/ForyJson.java b/java/fory-json/src/main/java/org/apache/fory/json/ForyJson.java
index 9848d54f8..c2989c3a8 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/ForyJson.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/ForyJson.java
@@ -556,7 +556,7 @@ public final class ForyJson {
byte coder = StringSerializer.getStringCoder(json);
if (StringSerializer.isLatin1Coder(coder)) {
// Keep String input on its reader owner even when ASCII Latin1 bytes match UTF-8;
- // custom JsonCodec implementations can observe readLatin1/readUtf16 dispatch.
+ // custom JsonValueCodec implementations can observe readLatin1/readUtf16 dispatch.
return readLatin1Value(state.latin1Reader(json), type, fallback, state);
}
if (StringSerializer.isUtf16Coder(coder)) {
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 be180e23c..6661c4686 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
@@ -20,7 +20,7 @@
package org.apache.fory.json;
import java.util.Objects;
-import org.apache.fory.json.codec.JsonCodec;
+import org.apache.fory.json.codec.JsonValueCodec;
import org.apache.fory.json.resolver.CodecRegistry;
/**
@@ -155,7 +155,7 @@ public final class ForyJsonBuilder {
* be thread-safe. Building snapshots the registration map, although the registered codec objects
* themselves are intentionally shared.
*/
- public <T> ForyJsonBuilder registerCodec(Class<T> type, JsonCodec<T> codec) {
+ public <T> ForyJsonBuilder registerCodec(Class<T> type, JsonValueCodec<T> codec) {
codecRegistry.register(type, codec);
return this;
}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/JsonTypeChecker.java b/java/fory-json/src/main/java/org/apache/fory/json/JsonTypeChecker.java
index 3a66d7786..52cf1be37 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/JsonTypeChecker.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/JsonTypeChecker.java
@@ -29,10 +29,10 @@ import org.apache.fory.exception.InsecureException;
* a String so class-name materialization paths can apply policy without requiring a second API.
*
* <p>Classes served by default built-in exact JSON codecs do not invoke the configured checker
- * unless a custom codec is registered for the same class. Arrays are checked through their ultimate
- * component type, and enum constant-specific subclasses are normalized to their enclosing enum.
- * Fory's disallow list always runs before this callback and cannot be bypassed by a built-in or
- * custom codec.
+ * unless a custom codec is registered for the same class or selected by {@code @JsonCodec}. Arrays
+ * are checked through their ultimate component type, and enum constant-specific subclasses are
+ * normalized to their enclosing enum. Fory's disallow list always runs before this callback and
+ * cannot be bypassed by a built-in or custom codec.
*
* <p>Decisions are shared by class name across the runtime's pooled states and cached up to a
* bounded number of distinct names. Once the cache is full, new names invoke the checker each time
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonCodec.java
new file mode 100644
index 000000000..1df86a175
--- /dev/null
+++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonCodec.java
@@ -0,0 +1,54 @@
+/*
+ * 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;
+import org.apache.fory.json.codec.JsonValueCodec;
+
+/**
+ * Selects the complete JSON value codec for a type declaration or one exact type-use occurrence.
+ *
+ * <p>On a class, record, enum, or interface declaration, this annotation defines an inheritable
+ * JSON representation contract. Fory traverses both superclass and interface declarations
+ * explicitly; this annotation deliberately does not use Java {@link java.lang.annotation.Inherited
+ * Inherited}. The most-specific declaration wins. Incomparable declarations that select different
+ * codec classes are rejected instead of being resolved by hierarchy traversal order. A concrete
+ * declaration, a codec on the current type use, or an exact builder registration can disambiguate
+ * such a hierarchy.
+ *
+ * <p>On a type use, this annotation applies only to that resolved value node. It can select the
+ * complete codec for a field, accessor or creator value, an array dimension or component, or a
+ * nested collection, map-value, optional, or atomic-reference node. It does not apply to map keys,
+ * which remain owned by {@link org.apache.fory.json.codec.MapCodec.MapKeyCodec}.
+ *
+ * <p>The selected {@link JsonValueCodec} reads and writes one complete JSON value, including JSON
+ * {@code null}, through Fory's concrete reader and writer APIs.
+ */
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.TYPE, ElementType.TYPE_USE})
+public @interface JsonCodec {
+ /** Returns the public, concrete codec class selected for this declaration or occurrence. */
+ Class<? extends JsonValueCodec<?>> value();
+}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/ArrayCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/ArrayCodec.java
index 1a681869e..c3b514e91 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/codec/ArrayCodec.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/ArrayCodec.java
@@ -21,6 +21,7 @@ package org.apache.fory.json.codec;
import java.lang.reflect.Array;
import java.util.Arrays;
+import org.apache.fory.annotation.Internal;
import org.apache.fory.json.ForyJsonException;
import org.apache.fory.json.reader.JsonReader;
import org.apache.fory.json.reader.Latin1JsonReader;
@@ -40,7 +41,7 @@ import org.apache.fory.json.writer.Utf8JsonWriter;
* operation rather than resolving a codec per element. Each concrete reader owns array allocation
* and growth because JSON carries no trusted element count.
*/
-public abstract class ArrayCodec<T> implements JsonCodec<T> {
+public abstract class ArrayCodec<T> implements JsonValueCodec<T> {
final Class<?> componentType;
ArrayCodec(Class<?> componentType) {
@@ -53,6 +54,15 @@ public abstract class ArrayCodec<T> implements JsonCodec<T> {
}
Class<?> componentType = arrayType.getComponentType();
JsonTypeInfo componentTypeInfo = resolver.getTypeInfo(componentType, componentType);
+ return create(arrayType, componentTypeInfo);
+ }
+
+ @Internal
+ public static <T> ArrayCodec<T> create(Class<T> arrayType, JsonTypeInfo componentTypeInfo) {
+ if (!arrayType.isArray()) {
+ throw new ForyJsonException("Unsupported JSON array type " + arrayType);
+ }
+ Class<?> componentType = arrayType.getComponentType();
Object componentCodec = componentTypeInfo.stringWriter();
if (componentType == int.class && componentCodec == ScalarCodecs.IntCodec.PRIMITIVE) {
return bind(IntArrayCodec.INSTANCE);
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/ClosedSubtypeCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/ClosedSubtypeCodec.java
index faff5041c..71d732083 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/codec/ClosedSubtypeCodec.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/ClosedSubtypeCodec.java
@@ -49,7 +49,7 @@ import org.apache.fory.json.writer.Utf8JsonWriter;
*/
@Internal
@SuppressWarnings("unchecked")
-public final class ClosedSubtypeCodec implements JsonCodec<Object> {
+public final class ClosedSubtypeCodec implements JsonValueCodec<Object> {
private final Class<?> baseType;
private final JsonSubTypesInfo definition;
private final JsonTypeInfo[] children;
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/CollectionCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/CollectionCodec.java
index 019791ec2..4f527df8e 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/codec/CollectionCodec.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/CollectionCodec.java
@@ -71,7 +71,7 @@ import org.apache.fory.reflect.TypeRef;
* count. Dynamic {@code Object} arrays are materialized as {@link JsonArray}, while typed targets
* use their selected factory.
*/
-public abstract class CollectionCodec<T extends Collection<?>> implements JsonCodec<T> {
+public abstract class CollectionCodec<T extends Collection<?>> implements JsonValueCodec<T> {
private static final Class<?> UNTYPED_COLLECTION = ArrayList.class;
private final CollectionFactory factory;
@@ -89,6 +89,17 @@ public abstract class CollectionCodec<T extends Collection<?>> implements JsonCo
Class<?> elementRawType = CodecUtils.rawType(elementType, Object.class);
CollectionFactory factory = collectionFactory(rawType, elementRawType);
JsonTypeInfo elementTypeInfo = resolver.getTypeInfo(elementType, elementRawType);
+ return create(factory, elementTypeInfo);
+ }
+
+ @Internal
+ public static CollectionCodec<?> create(
+ Class<?> rawType, Class<?> elementRawType, JsonTypeInfo elementTypeInfo) {
+ return create(collectionFactory(rawType, elementRawType), elementTypeInfo);
+ }
+
+ private static CollectionCodec<?> create(
+ CollectionFactory factory, JsonTypeInfo elementTypeInfo) {
Object elementCodec = elementTypeInfo.stringWriter();
if (elementCodec == ScalarCodecs.StringCodec.INSTANCE) {
return new StringCollectionCodec(factory);
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/GuavaCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/GuavaCodecs.java
index 5fb532a84..09b5f3d57 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/codec/GuavaCodecs.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/GuavaCodecs.java
@@ -70,7 +70,7 @@ public final class GuavaCodecs {
private GuavaCodecs() {}
- public static void registerExactCodecs(Map<Class<?>, JsonCodec<?>> exactCodecs) {
+ public static void registerExactCodecs(Map<Class<?>, JsonValueCodec<?>> exactCodecs) {
if (IMMUTABLE_INT_ARRAY_AVAILABLE) {
Direct.registerExactCodecs(exactCodecs);
}
@@ -140,7 +140,7 @@ public final class GuavaCodecs {
private static final class Direct {
private Direct() {}
- private static void registerExactCodecs(Map<Class<?>, JsonCodec<?>> exactCodecs) {
+ private static void registerExactCodecs(Map<Class<?>, JsonValueCodec<?>> exactCodecs) {
exactCodecs.put(ImmutableIntArray.class, ImmutableIntArrayCodec.INSTANCE);
}
@@ -226,7 +226,7 @@ public final class GuavaCodecs {
}
}
- private static final class ImmutableIntArrayCodec implements JsonCodec<ImmutableIntArray> {
+ private static final class ImmutableIntArrayCodec implements JsonValueCodec<ImmutableIntArray> {
private static final ImmutableIntArrayCodec INSTANCE = new ImmutableIntArrayCodec();
private ImmutableIntArrayCodec() {}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/JsonCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/JsonValueCodec.java
similarity index 67%
rename from java/fory-json/src/main/java/org/apache/fory/json/codec/JsonCodec.java
rename to java/fory-json/src/main/java/org/apache/fory/json/codec/JsonValueCodec.java
index 102b61076..cf686c275 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/codec/JsonCodec.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/JsonValueCodec.java
@@ -20,18 +20,23 @@
package org.apache.fory.json.codec;
/**
- * Typed semantic codec composed from the five concrete JSON input and output capabilities.
+ * A streaming codec for one complete JSON value of type {@code T}.
+ *
+ * <p>The codec reads from and writes to Fory JSON's concrete readers and writers directly; it is
+ * not a JSON abstract syntax tree (AST) codec. Each operation owns the complete value, including
+ * its JSON {@code null} representation. There is no secondary non-null codec protocol: field
+ * omission belongs to object-field handling, while primitive null rejection belongs to the
+ * primitive codec or primitive field owner.
+ *
+ * <p>A value codec never handles map keys. Map keys are encoded and decoded by {@link
+ * MapCodec.MapKeyCodec}.
*
* <p>Built-in and user-registered codecs implement this complete interface because one codec owns
* the Java type's semantics for every representation. Generated object specializations implement
* only the narrow capability they accelerate and are installed independently in the corresponding
* {@link org.apache.fory.json.resolver.JsonTypeInfo} slot.
- *
- * <p>Each capability consumes or writes the complete value, including its null representation.
- * There is no secondary non-null codec protocol; field omission belongs to object-field handling,
- * while primitive null rejection belongs to the primitive codec or primitive field owner.
*/
-public interface JsonCodec<T>
+public interface JsonValueCodec<T>
extends StringWriterCodec<T>,
Utf8WriterCodec<T>,
Latin1ReaderCodec<T>,
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/MapCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/MapCodec.java
index dd0a5465a..f5169d678 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/codec/MapCodec.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/MapCodec.java
@@ -32,6 +32,7 @@ import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
+import org.apache.fory.annotation.Internal;
import org.apache.fory.collection.Tuple2;
import org.apache.fory.json.ForyJsonException;
import org.apache.fory.json.JsonObject;
@@ -61,7 +62,7 @@ import org.apache.fory.reflect.TypeRef;
* Object} values use insertion-ordered {@link JsonObject}; typed targets use the selected map
* factory and optional immutable finish conversion.
*/
-public abstract class MapCodec<T extends Map<?, ?>> implements JsonCodec<T> {
+public abstract class MapCodec<T extends Map<?, ?>> implements JsonValueCodec<T> {
private static final Class<?> UNTYPED_MAP = LinkedHashMap.class;
private final MapFactory factory;
@@ -77,9 +78,20 @@ public abstract class MapCodec<T extends Map<?, ?>> implements JsonCodec<T> {
Class<?> keyRawType = CodecUtils.rawType(keyType, Object.class);
Type valueType = keyValueTypeRefs.f1.getType();
Class<?> valueRawType = CodecUtils.rawType(valueType, Object.class);
- resolver.checkSecure(keyRawType);
+ resolver.checkMapKeySecure(keyRawType);
MapFactory factory = mapFactory(rawType, keyRawType);
JsonTypeInfo valueTypeInfo = resolver.getTypeInfo(valueType, valueRawType);
+ return create(factory, keyRawType, valueTypeInfo);
+ }
+
+ @Internal
+ public static MapCodec<?> create(
+ Class<?> rawType, Class<?> keyRawType, JsonTypeInfo valueTypeInfo) {
+ return create(mapFactory(rawType, keyRawType), keyRawType, valueTypeInfo);
+ }
+
+ private static MapCodec<?> create(
+ MapFactory factory, Class<?> keyRawType, JsonTypeInfo valueTypeInfo) {
Object valueCodec = valueTypeInfo.stringWriter();
if (keyRawType == String.class) {
if (valueCodec == ScalarCodecs.StringCodec.INSTANCE) {
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 d7c5d7674..71c44dd7d 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
@@ -36,6 +36,7 @@ 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.meta.JsonFieldTable;
+import org.apache.fory.json.meta.JsonTypeUse;
import org.apache.fory.json.reader.Latin1JsonReader;
import org.apache.fory.json.reader.Utf16JsonReader;
import org.apache.fory.json.reader.Utf8JsonReader;
@@ -66,7 +67,7 @@ import org.apache.fory.util.record.RecordUtils;
* Generated code may replace paths independently, but it is built from this codec's immutable field
* metadata and preserves the same null, unknown-field, record, and member-discovery semantics.
*/
-public class ObjectCodec<T> implements JsonCodec<T> {
+public class ObjectCodec<T> implements JsonValueCodec<T> {
private static final int MUTABLE = 0;
private static final int RECORD = 1;
private static final int CREATOR = 2;
@@ -111,13 +112,25 @@ public class ObjectCodec<T> implements JsonCodec<T> {
}
}
+ @Internal
+ public static <T> ObjectCodec<T> build(
+ TypeRef<T> ownerType,
+ boolean propertyDiscoveryEnabled,
+ PropertyNamingStrategy propertyNamingStrategy,
+ boolean writeNullFields) {
+ return build(
+ ownerType, null, propertyDiscoveryEnabled, propertyNamingStrategy, writeNullFields);
+ }
+
+ @Internal
public static <T> ObjectCodec<T> build(
TypeRef<T> ownerType,
+ JsonTypeUse ownerTypeUse,
boolean propertyDiscoveryEnabled,
PropertyNamingStrategy propertyNamingStrategy,
boolean writeNullFields) {
return ObjectCodecBuilder.build(
- ownerType, propertyDiscoveryEnabled, propertyNamingStrategy, writeNullFields);
+ ownerType, ownerTypeUse, propertyDiscoveryEnabled, propertyNamingStrategy, writeNullFields);
}
static <T> ObjectCodec<T> createCodec(
@@ -1182,6 +1195,7 @@ public class ObjectCodec<T> implements JsonCodec<T> {
private final Class<?> mapRawType;
private final Type valueType;
private final Class<?> valueRawType;
+ private final JsonTypeUse valueTypeUse;
private final int writeIndex;
private final int constructionIndex;
private JsonTypeInfo valueTypeInfo;
@@ -1196,6 +1210,7 @@ public class ObjectCodec<T> implements JsonCodec<T> {
Class<?> mapRawType,
Type valueType,
Class<?> valueRawType,
+ JsonTypeUse valueTypeUse,
int writeIndex,
int constructionIndex) {
this.writeField = writeField;
@@ -1217,14 +1232,24 @@ public class ObjectCodec<T> implements JsonCodec<T> {
this.mapRawType = mapRawType;
this.valueType = valueType;
this.valueRawType = valueRawType;
+ this.valueTypeUse = valueTypeUse;
this.writeIndex = writeIndex;
this.constructionIndex = constructionIndex;
}
private void resolveTypes(JsonTypeResolver resolver) {
- valueTypeInfo = resolver.getTypeInfo(valueType, valueRawType);
+ if (readField != null && valueTypeUse != null) {
+ resolver.checkMapKeySecure(String.class);
+ }
+ valueTypeInfo =
+ valueTypeUse == null
+ ? resolver.getTypeInfo(valueType, valueRawType)
+ : resolver.getTypeInfo(valueTypeUse);
if (readField != null) {
- mapCodec = MapCodec.create(mapRawType, TypeRef.of(mapType), resolver);
+ mapCodec =
+ valueTypeUse == null
+ ? MapCodec.create(mapRawType, TypeRef.of(mapType), resolver)
+ : MapCodec.create(mapRawType, String.class, valueTypeInfo);
}
}
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 1e507f0dc..e0019e15a 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
@@ -50,6 +50,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.meta.JsonTypeUse;
import org.apache.fory.reflect.ObjectInstantiator;
import org.apache.fory.reflect.ObjectInstantiators;
import org.apache.fory.reflect.TypeRef;
@@ -62,6 +63,7 @@ final class ObjectCodecBuilder {
static <T> ObjectCodec<T> build(
TypeRef<T> ownerType,
+ JsonTypeUse ownerTypeUse,
boolean propertyDiscoveryEnabled,
PropertyNamingStrategy propertyNamingStrategy,
boolean writeNullFields) {
@@ -99,7 +101,7 @@ final class ObjectCodecBuilder {
JsonCreatorInfo creatorInfo =
record
? rejectRecordCreator(type)
- : buildCreatorInfo(type, ownerType, builders, propertyNamingStrategy);
+ : buildCreatorInfo(type, ownerType, ownerTypeUse, builders, propertyNamingStrategy);
if (anySetter != null && (record || creatorInfo != null)) {
throw new ForyJsonException(
"@JsonAnySetter is not supported on constructor-backed type " + type.getName());
@@ -187,7 +189,7 @@ final class ObjectCodecBuilder {
continue;
}
JsonFieldInfo field =
- builder.build(record, ownerType, propertyNamingStrategy, writeNullFields);
+ builder.build(record, ownerType, ownerTypeUse, propertyNamingStrategy, writeNullFields);
if (!hasAny) {
FieldBuilder priorProperty = canonicalNames.put(field.name(), builder);
if (priorProperty != null) {
@@ -262,7 +264,8 @@ final class ObjectCodecBuilder {
}
AnyInfo anyInfo =
hasAny
- ? buildAnyInfo(ownerType, anyBuilder, anySetter, anyWriteIndex, constructionIndex)
+ ? buildAnyInfo(
+ ownerType, ownerTypeUse, anyBuilder, anySetter, anyWriteIndex, constructionIndex)
: null;
ObjectInstantiator<?> instantiator = ObjectInstantiators.createObjectInstantiator(type);
String[] recordNames = record ? readJavaNames.toArray(new String[0]) : null;
@@ -685,6 +688,7 @@ final class ObjectCodecBuilder {
// optimized read/write owner. The accessor participates only in logical-property annotation
// merging and is discarded before hot metadata is published.
builder.mergeAnnotation(type, component.getAccessor());
+ builder.setRecordComponent(component);
}
}
@@ -705,6 +709,7 @@ final class ObjectCodecBuilder {
private static JsonCreatorInfo buildCreatorInfo(
Class<?> type,
TypeRef<?> ownerType,
+ JsonTypeUse ownerTypeUse,
LinkedHashMap<String, FieldBuilder> builders,
PropertyNamingStrategy namingStrategy) {
Executable creator = null;
@@ -789,8 +794,11 @@ final class ObjectCodecBuilder {
}
if (!builder.isAny()) {
Type resolved = ownerType.resolveType(parameterTypes[i]).getType();
+ JsonTypeUse typeUse =
+ builder.resolveTypeUse(ownerType, ownerTypeUse, "creator property " + javaName);
fields.add(
- new JsonCreatorFieldInfo(builder.jsonName(namingStrategy), i, resolved, rawTypes[i]));
+ new JsonCreatorFieldInfo(
+ builder.jsonName(namingStrategy), i, resolved, rawTypes[i], typeUse));
}
}
} else {
@@ -841,7 +849,19 @@ final class ObjectCodecBuilder {
}
}
Type resolved = ownerType.resolveType(parameterTypes[i]).getType();
- fields.add(new JsonCreatorFieldInfo(jsonName, i, resolved, rawTypes[i]));
+ JsonTypeUse typeUse;
+ if (builder == null) {
+ typeUse =
+ JsonTypeUse.resolveMember(
+ ownerType,
+ ownerTypeUse,
+ parameterTypes[i],
+ executableParameterTypeUse(creator, i),
+ "creator property " + jsonName);
+ } else {
+ typeUse = builder.resolveTypeUse(ownerType, ownerTypeUse, "creator property " + jsonName);
+ }
+ fields.add(new JsonCreatorFieldInfo(jsonName, i, resolved, rawTypes[i], typeUse));
}
}
JsonCreatorFieldInfo[] fieldArray = fields.toArray(new JsonCreatorFieldInfo[0]);
@@ -903,6 +923,13 @@ final class ObjectCodecBuilder {
+ parameterIndex);
}
builder.creatorArgumentIndex = parameterIndex;
+ builder.setCreatorType(creator, parameterIndex, parameterType);
+ }
+
+ private static JsonTypeUse executableParameterTypeUse(Executable executable, int parameterIndex) {
+ return executable instanceof Method
+ ? JsonTypeUse.forMethodParameter((Method) executable, parameterIndex)
+ : JsonTypeUse.forConstructorParameter((Constructor<?>) executable, parameterIndex);
}
private static void rejectCreatorHashCollisions(JsonCreatorFieldInfo[] fields) {
@@ -1117,6 +1144,7 @@ final class ObjectCodecBuilder {
private static AnyInfo buildAnyInfo(
TypeRef<?> ownerType,
+ JsonTypeUse ownerTypeUse,
FieldBuilder builder,
Method anySetter,
int writeIndex,
@@ -1130,6 +1158,7 @@ final class ObjectCodecBuilder {
Class<?> mapRawType = null;
Type valueType = null;
Class<?> valueRawType = null;
+ JsonTypeUse valueTypeUse = null;
if (anyField != null || anyGetter != null) {
Type declaredMapType =
anyGetter == null ? anyField.getGenericType() : anyGetter.getGenericReturnType();
@@ -1138,6 +1167,23 @@ final class ObjectCodecBuilder {
valueType = anyMapValueType(mapType, mapRawType, anyField != null ? anyField : anyGetter);
valueRawType = CodecUtils.rawType(valueType, Object.class);
validateAnyLogicalTypes(ownerType, builder, mapType);
+ JsonTypeUse mapTypeUse =
+ builder.resolveTypeUse(ownerType, ownerTypeUse, "JSON Any property " + builder.name);
+ if (mapTypeUse != null) {
+ if (mapTypeUse.hasCodec()) {
+ throw new ForyJsonException(
+ "@JsonCodec from "
+ + mapTypeUse.codecSource()
+ + " cannot select the flattened JSON Any map");
+ }
+ JsonTypeUse projected =
+ mapTypeUse.projectTo(Map.class, "JSON Any property " + builder.name);
+ projected.argument(0).rejectMapKey("JSON Any property " + builder.name);
+ valueTypeUse = projected.argument(1);
+ if (!valueTypeUse.hasExplicitCodec()) {
+ valueTypeUse = null;
+ }
+ }
}
if (anySetter != null) {
Type setterType = ownerType.resolveType(anySetter.getGenericParameterTypes()[1]).getType();
@@ -1155,6 +1201,25 @@ final class ObjectCodecBuilder {
valueType = setterType;
valueRawType = setterRawType;
}
+ JsonTypeUse setterKeyUse =
+ JsonTypeUse.resolveMember(
+ ownerType,
+ ownerTypeUse,
+ anySetter.getGenericParameterTypes()[0],
+ JsonTypeUse.forMethodParameter(anySetter, 0),
+ "JSON Any setter key");
+ if (setterKeyUse != null) {
+ setterKeyUse.rejectMapKey("JSON Any setter");
+ }
+ JsonTypeUse setterValueUse =
+ JsonTypeUse.resolveMember(
+ ownerType,
+ ownerTypeUse,
+ anySetter.getGenericParameterTypes()[1],
+ JsonTypeUse.forMethodParameter(anySetter, 1),
+ "JSON Any setter value");
+ valueTypeUse =
+ JsonTypeUse.merge(valueTypeUse, setterValueUse, "JSON Any value on " + ownerType);
}
return new AnyInfo(
writeField,
@@ -1165,6 +1230,7 @@ final class ObjectCodecBuilder {
mapRawType,
valueType,
valueRawType,
+ valueTypeUse,
writeIndex,
constructionIndex);
}
@@ -1270,6 +1336,12 @@ final class ObjectCodecBuilder {
private AnnotatedElement explicitIncludeSource;
private boolean hasJsonProperty;
private int creatorArgumentIndex = -1;
+ private JsonTypeUse fieldTypeUse;
+ private JsonTypeUse writeGetterTypeUse;
+ private JsonTypeUse readSetterTypeUse;
+ private RecordComponent recordComponent;
+ private JsonTypeUse creatorTypeUse;
+ private Type creatorType;
private FieldBuilder(String name) {
this.name = name;
@@ -1286,6 +1358,7 @@ final class ObjectCodecBuilder {
throw new ForyJsonException("Duplicate JSON field " + name);
}
this.field = field;
+ fieldTypeUse = JsonTypeUse.forField(field);
fieldWriteAllowed = writeAllowed;
fieldReadAllowed = readAllowed;
if (writeSource) {
@@ -1305,6 +1378,7 @@ final class ObjectCodecBuilder {
private void setWriteGetter(Class<?> type, Method getter) {
mergeAnnotation(type, getter);
+ writeGetterTypeUse = JsonTypeUse.forMethodReturn(getter);
if (field != null && !fieldWriteAllowed) {
return;
}
@@ -1317,6 +1391,7 @@ final class ObjectCodecBuilder {
private void setReadSetter(Class<?> type, Method setter) {
mergeAnnotation(type, setter);
+ readSetterTypeUse = JsonTypeUse.forMethodParameter(setter, 0);
if (field != null && !fieldReadAllowed) {
return;
}
@@ -1329,6 +1404,7 @@ final class ObjectCodecBuilder {
private void setAnyGetter(Class<?> type, Method getter) {
mergeAnnotation(type, getter);
+ writeGetterTypeUse = JsonTypeUse.forMethodReturn(getter);
if (field != null && !fieldWriteAllowed) {
throw new ForyJsonException(
"@JsonIgnore disables the same-name @JsonAnyGetter on " + getter);
@@ -1412,6 +1488,7 @@ final class ObjectCodecBuilder {
private JsonFieldInfo build(
boolean record,
TypeRef<?> ownerType,
+ JsonTypeUse ownerTypeUse,
PropertyNamingStrategy propertyNamingStrategy,
boolean defaultWriteNull) {
validateTypes(ownerType);
@@ -1437,6 +1514,7 @@ final class ObjectCodecBuilder {
readSetter != null
? JsonFieldAccessor.forSetter(readSetter)
: (readField == null || record ? null : JsonFieldAccessor.forField(readField));
+ JsonTypeUse typeUse = resolveTypeUse(ownerType, ownerTypeUse, "JSON property " + name);
return new JsonFieldInfo(
jsonName,
writeNull,
@@ -1446,7 +1524,64 @@ final class ObjectCodecBuilder {
readSetter,
writeAccessor,
readAccessor,
- ownerType);
+ ownerType,
+ typeUse);
+ }
+
+ private void setRecordComponent(RecordComponent component) {
+ recordComponent = component;
+ }
+
+ private void setCreatorType(Executable creator, int parameterIndex, Type parameterType) {
+ creatorType = parameterType;
+ creatorTypeUse = executableParameterTypeUse(creator, parameterIndex);
+ }
+
+ private JsonTypeUse resolveTypeUse(
+ TypeRef<?> ownerType, JsonTypeUse ownerTypeUse, String path) {
+ JsonTypeUse resolved = null;
+ if (field != null) {
+ resolved =
+ JsonTypeUse.resolveMember(
+ ownerType, ownerTypeUse, field.getGenericType(), fieldTypeUse, path + " field");
+ }
+ if (writeGetter != null) {
+ JsonTypeUse getterUse =
+ JsonTypeUse.resolveMember(
+ ownerType,
+ ownerTypeUse,
+ writeGetter.getGenericReturnType(),
+ writeGetterTypeUse,
+ path + " getter");
+ resolved = JsonTypeUse.merge(resolved, getterUse, path);
+ }
+ if (readSetter != null) {
+ JsonTypeUse setterUse =
+ JsonTypeUse.resolveMember(
+ ownerType,
+ ownerTypeUse,
+ readSetter.getGenericParameterTypes()[0],
+ readSetterTypeUse,
+ path + " setter");
+ resolved = JsonTypeUse.merge(resolved, setterUse, path);
+ }
+ if (recordComponent != null) {
+ JsonTypeUse componentUse =
+ JsonTypeUse.resolveMember(
+ ownerType,
+ ownerTypeUse,
+ recordComponent.getGenericType(),
+ JsonTypeUse.forRecordComponent(recordComponent),
+ path + " record component");
+ resolved = JsonTypeUse.merge(resolved, componentUse, path);
+ }
+ if (creatorType != null) {
+ JsonTypeUse parameterUse =
+ JsonTypeUse.resolveMember(
+ ownerType, ownerTypeUse, creatorType, creatorTypeUse, path + " creator parameter");
+ resolved = JsonTypeUse.merge(resolved, parameterUse, path);
+ }
+ return resolved;
}
private void mergeAnnotation(Class<?> type, AnnotatedElement source) {
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/ScalarCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/ScalarCodecs.java
index b5215bbda..dd1ad5e80 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/codec/ScalarCodecs.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/ScalarCodecs.java
@@ -71,6 +71,7 @@ import java.util.concurrent.atomic.AtomicLongArray;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.regex.Pattern;
+import org.apache.fory.annotation.Internal;
import org.apache.fory.json.ForyJsonException;
import org.apache.fory.json.meta.JsonAsciiToken;
import org.apache.fory.json.meta.JsonFieldNameHash;
@@ -114,7 +115,7 @@ public final class ScalarCodecs {
private ScalarCodecs() {}
- public static final class NaturalCodec implements JsonCodec<Object> {
+ public static final class NaturalCodec implements JsonValueCodec<Object> {
public static final NaturalCodec INSTANCE = new NaturalCodec();
private NaturalCodec() {}
@@ -194,7 +195,7 @@ public final class ScalarCodecs {
}
}
- public static final class StringCodec implements JsonCodec<String> {
+ public static final class StringCodec implements JsonValueCodec<String> {
public static final StringCodec INSTANCE = new StringCodec();
private StringCodec() {}
@@ -233,7 +234,7 @@ public final class ScalarCodecs {
}
}
- public static final class CharSequenceCodec implements JsonCodec<CharSequence> {
+ public static final class CharSequenceCodec implements JsonValueCodec<CharSequence> {
public static final CharSequenceCodec INSTANCE = new CharSequenceCodec();
private CharSequenceCodec() {}
@@ -272,7 +273,7 @@ public final class ScalarCodecs {
}
}
- public static final class VoidCodec implements JsonCodec<Void> {
+ public static final class VoidCodec implements JsonValueCodec<Void> {
public static final VoidCodec INSTANCE = new VoidCodec();
@Override
@@ -304,7 +305,7 @@ public final class ScalarCodecs {
}
}
- public static final class BooleanCodec implements JsonCodec<Boolean> {
+ public static final class BooleanCodec implements JsonValueCodec<Boolean> {
public static final BooleanCodec PRIMITIVE = new BooleanCodec(true);
public static final BooleanCodec BOXED = new BooleanCodec(false);
private final boolean primitive;
@@ -356,7 +357,7 @@ public final class ScalarCodecs {
}
}
- public static final class IntCodec implements JsonCodec<Integer> {
+ public static final class IntCodec implements JsonValueCodec<Integer> {
public static final IntCodec PRIMITIVE = new IntCodec(true);
public static final IntCodec BOXED = new IntCodec(false);
private final boolean primitive;
@@ -408,7 +409,7 @@ public final class ScalarCodecs {
}
}
- public static final class LongCodec implements JsonCodec<Long> {
+ public static final class LongCodec implements JsonValueCodec<Long> {
public static final LongCodec PRIMITIVE = new LongCodec(true);
public static final LongCodec BOXED = new LongCodec(false);
private final boolean primitive;
@@ -460,7 +461,7 @@ public final class ScalarCodecs {
}
}
- public static final class ShortCodec implements JsonCodec<Short> {
+ public static final class ShortCodec implements JsonValueCodec<Short> {
public static final ShortCodec PRIMITIVE = new ShortCodec(true);
public static final ShortCodec BOXED = new ShortCodec(false);
private final boolean primitive;
@@ -519,7 +520,7 @@ public final class ScalarCodecs {
}
}
- public static final class ByteCodec implements JsonCodec<Byte> {
+ public static final class ByteCodec implements JsonValueCodec<Byte> {
public static final ByteCodec PRIMITIVE = new ByteCodec(true);
public static final ByteCodec BOXED = new ByteCodec(false);
private final boolean primitive;
@@ -578,7 +579,7 @@ public final class ScalarCodecs {
}
}
- public static final class FloatCodec implements JsonCodec<Float> {
+ public static final class FloatCodec implements JsonValueCodec<Float> {
public static final FloatCodec PRIMITIVE = new FloatCodec(true);
public static final FloatCodec BOXED = new FloatCodec(false);
private final boolean primitive;
@@ -630,7 +631,7 @@ public final class ScalarCodecs {
}
}
- public static final class DoubleCodec implements JsonCodec<Double> {
+ public static final class DoubleCodec implements JsonValueCodec<Double> {
public static final DoubleCodec PRIMITIVE = new DoubleCodec(true);
public static final DoubleCodec BOXED = new DoubleCodec(false);
private final boolean primitive;
@@ -682,7 +683,7 @@ public final class ScalarCodecs {
}
}
- public static final class CharCodec implements JsonCodec<Character> {
+ public static final class CharCodec implements JsonValueCodec<Character> {
public static final CharCodec PRIMITIVE = new CharCodec(true);
public static final CharCodec BOXED = new CharCodec(false);
private final boolean primitive;
@@ -746,7 +747,7 @@ public final class ScalarCodecs {
return new ForyJsonException("Invalid " + type.getName() + " JSON string: " + value, cause);
}
- public static final class NumberCodec implements JsonCodec<Number> {
+ public static final class NumberCodec implements JsonValueCodec<Number> {
public static final NumberCodec INSTANCE = new NumberCodec();
private NumberCodec() {}
@@ -848,7 +849,7 @@ public final class ScalarCodecs {
}
}
- public static final class BigIntegerCodec implements JsonCodec<BigInteger> {
+ public static final class BigIntegerCodec implements JsonValueCodec<BigInteger> {
public static final BigIntegerCodec INSTANCE = new BigIntegerCodec();
@Override
@@ -885,7 +886,7 @@ public final class ScalarCodecs {
}
}
- public static final class BigDecimalCodec implements JsonCodec<BigDecimal> {
+ public static final class BigDecimalCodec implements JsonValueCodec<BigDecimal> {
public static final BigDecimalCodec INSTANCE = new BigDecimalCodec();
@Override
@@ -922,7 +923,7 @@ public final class ScalarCodecs {
}
}
- public static final class Float16Codec implements JsonCodec<Float16> {
+ public static final class Float16Codec implements JsonValueCodec<Float16> {
public static final Float16Codec INSTANCE = new Float16Codec();
@Override
@@ -959,7 +960,7 @@ public final class ScalarCodecs {
}
}
- public static final class BFloat16Codec implements JsonCodec<BFloat16> {
+ public static final class BFloat16Codec implements JsonValueCodec<BFloat16> {
public static final BFloat16Codec INSTANCE = new BFloat16Codec();
@Override
@@ -996,7 +997,7 @@ public final class ScalarCodecs {
}
}
- public static final class BitSetCodec implements JsonCodec<BitSet> {
+ public static final class BitSetCodec implements JsonValueCodec<BitSet> {
public static final BitSetCodec INSTANCE = new BitSetCodec();
private BitSetCodec() {}
@@ -1115,7 +1116,7 @@ public final class ScalarCodecs {
}
}
- public static final class StringBuilderCodec implements JsonCodec<StringBuilder> {
+ public static final class StringBuilderCodec implements JsonValueCodec<StringBuilder> {
public static final StringBuilderCodec INSTANCE = new StringBuilderCodec();
@Override
@@ -1155,7 +1156,7 @@ public final class ScalarCodecs {
}
}
- public static final class StringBufferCodec implements JsonCodec<StringBuffer> {
+ public static final class StringBufferCodec implements JsonValueCodec<StringBuffer> {
public static final StringBufferCodec INSTANCE = new StringBufferCodec();
@Override
@@ -1195,7 +1196,7 @@ public final class ScalarCodecs {
}
}
- public static final class FileCodec implements JsonCodec<File> {
+ public static final class FileCodec implements JsonValueCodec<File> {
public static final FileCodec INSTANCE = new FileCodec();
@Override
@@ -1235,7 +1236,7 @@ public final class ScalarCodecs {
}
}
- public static final class PathCodec implements JsonCodec<Path> {
+ public static final class PathCodec implements JsonValueCodec<Path> {
public static final PathCodec INSTANCE = new PathCodec();
@Override
@@ -1296,7 +1297,7 @@ public final class ScalarCodecs {
}
}
- public static final class CurrencyCodec implements JsonCodec<Currency> {
+ public static final class CurrencyCodec implements JsonValueCodec<Currency> {
public static final CurrencyCodec INSTANCE = new CurrencyCodec();
@Override
@@ -1357,7 +1358,7 @@ public final class ScalarCodecs {
}
}
- public static final class UriCodec implements JsonCodec<URI> {
+ public static final class UriCodec implements JsonValueCodec<URI> {
public static final UriCodec INSTANCE = new UriCodec();
@Override
@@ -1418,7 +1419,7 @@ public final class ScalarCodecs {
}
}
- public static final class PatternCodec implements JsonCodec<Pattern> {
+ public static final class PatternCodec implements JsonValueCodec<Pattern> {
public static final PatternCodec INSTANCE = new PatternCodec();
@Override
@@ -1479,7 +1480,7 @@ public final class ScalarCodecs {
}
}
- public static final class UuidCodec implements JsonCodec<UUID> {
+ public static final class UuidCodec implements JsonValueCodec<UUID> {
public static final UuidCodec INSTANCE = new UuidCodec();
@Override
@@ -1516,7 +1517,7 @@ public final class ScalarCodecs {
}
}
- public static final class LocaleCodec implements JsonCodec<Locale> {
+ public static final class LocaleCodec implements JsonValueCodec<Locale> {
public static final LocaleCodec INSTANCE = new LocaleCodec();
@Override
@@ -1556,7 +1557,7 @@ public final class ScalarCodecs {
}
}
- public static final class CharsetCodec implements JsonCodec<Charset> {
+ public static final class CharsetCodec implements JsonValueCodec<Charset> {
public static final CharsetCodec INSTANCE = new CharsetCodec();
@Override
@@ -1617,7 +1618,7 @@ public final class ScalarCodecs {
}
}
- public static final class DateCodec implements JsonCodec<Date> {
+ public static final class DateCodec implements JsonValueCodec<Date> {
public static final DateCodec INSTANCE = new DateCodec();
@Override
@@ -1654,7 +1655,7 @@ public final class ScalarCodecs {
}
}
- public static final class CalendarCodec implements JsonCodec<Calendar> {
+ public static final class CalendarCodec implements JsonValueCodec<Calendar> {
public static final CalendarCodec INSTANCE = new CalendarCodec();
@Override
@@ -1697,7 +1698,7 @@ public final class ScalarCodecs {
}
}
- public static final class TimeZoneCodec implements JsonCodec<TimeZone> {
+ public static final class TimeZoneCodec implements JsonValueCodec<TimeZone> {
public static final TimeZoneCodec INSTANCE = new TimeZoneCodec();
@Override
@@ -1737,7 +1738,7 @@ public final class ScalarCodecs {
}
}
- public static final class LocalDateCodec implements JsonCodec<LocalDate> {
+ public static final class LocalDateCodec implements JsonValueCodec<LocalDate> {
public static final LocalDateCodec INSTANCE = new LocalDateCodec();
@Override
@@ -1774,7 +1775,7 @@ public final class ScalarCodecs {
}
}
- public static final class LocalTimeCodec implements JsonCodec<LocalTime> {
+ public static final class LocalTimeCodec implements JsonValueCodec<LocalTime> {
public static final LocalTimeCodec INSTANCE = new LocalTimeCodec();
@Override
@@ -1811,7 +1812,7 @@ public final class ScalarCodecs {
}
}
- public static final class LocalDateTimeCodec implements JsonCodec<LocalDateTime> {
+ public static final class LocalDateTimeCodec implements JsonValueCodec<LocalDateTime> {
public static final LocalDateTimeCodec INSTANCE = new LocalDateTimeCodec();
@Override
@@ -1848,7 +1849,7 @@ public final class ScalarCodecs {
}
}
- public static final class InstantCodec implements JsonCodec<Instant> {
+ public static final class InstantCodec implements JsonValueCodec<Instant> {
public static final InstantCodec INSTANCE = new InstantCodec();
@Override
@@ -1885,7 +1886,7 @@ public final class ScalarCodecs {
}
}
- public static final class DurationCodec implements JsonCodec<Duration> {
+ public static final class DurationCodec implements JsonValueCodec<Duration> {
public static final DurationCodec INSTANCE = new DurationCodec();
@Override
@@ -1922,7 +1923,7 @@ public final class ScalarCodecs {
}
}
- public static final class ZoneOffsetCodec implements JsonCodec<ZoneOffset> {
+ public static final class ZoneOffsetCodec implements JsonValueCodec<ZoneOffset> {
public static final ZoneOffsetCodec INSTANCE = new ZoneOffsetCodec();
@Override
@@ -1959,7 +1960,7 @@ public final class ScalarCodecs {
}
}
- public static final class ZoneIdCodec implements JsonCodec<ZoneId> {
+ public static final class ZoneIdCodec implements JsonValueCodec<ZoneId> {
public static final ZoneIdCodec INSTANCE = new ZoneIdCodec();
@Override
@@ -2020,7 +2021,7 @@ public final class ScalarCodecs {
}
}
- public static final class ZonedDateTimeCodec implements JsonCodec<ZonedDateTime> {
+ public static final class ZonedDateTimeCodec implements JsonValueCodec<ZonedDateTime> {
public static final ZonedDateTimeCodec INSTANCE = new ZonedDateTimeCodec();
@Override
@@ -2057,7 +2058,7 @@ public final class ScalarCodecs {
}
}
- public static final class YearCodec implements JsonCodec<Year> {
+ public static final class YearCodec implements JsonValueCodec<Year> {
public static final YearCodec INSTANCE = new YearCodec();
@Override
@@ -2094,7 +2095,7 @@ public final class ScalarCodecs {
}
}
- public static final class YearMonthCodec implements JsonCodec<YearMonth> {
+ public static final class YearMonthCodec implements JsonValueCodec<YearMonth> {
public static final YearMonthCodec INSTANCE = new YearMonthCodec();
@Override
@@ -2131,7 +2132,7 @@ public final class ScalarCodecs {
}
}
- public static final class MonthDayCodec implements JsonCodec<MonthDay> {
+ public static final class MonthDayCodec implements JsonValueCodec<MonthDay> {
public static final MonthDayCodec INSTANCE = new MonthDayCodec();
@Override
@@ -2168,7 +2169,7 @@ public final class ScalarCodecs {
}
}
- public static final class PeriodCodec implements JsonCodec<Period> {
+ public static final class PeriodCodec implements JsonValueCodec<Period> {
public static final PeriodCodec INSTANCE = new PeriodCodec();
@Override
@@ -2205,7 +2206,7 @@ public final class ScalarCodecs {
}
}
- public static final class OffsetTimeCodec implements JsonCodec<OffsetTime> {
+ public static final class OffsetTimeCodec implements JsonValueCodec<OffsetTime> {
public static final OffsetTimeCodec INSTANCE = new OffsetTimeCodec();
@Override
@@ -2242,7 +2243,7 @@ public final class ScalarCodecs {
}
}
- public static final class OffsetDateTimeCodec implements JsonCodec<OffsetDateTime> {
+ public static final class OffsetDateTimeCodec implements JsonValueCodec<OffsetDateTime> {
public static final OffsetDateTimeCodec INSTANCE = new OffsetDateTimeCodec();
@Override
@@ -2279,7 +2280,7 @@ public final class ScalarCodecs {
}
}
- public static final class HijrahDateCodec implements JsonCodec<HijrahDate> {
+ public static final class HijrahDateCodec implements JsonValueCodec<HijrahDate> {
public static final HijrahDateCodec INSTANCE = new HijrahDateCodec();
@Override
@@ -2340,7 +2341,7 @@ public final class ScalarCodecs {
}
}
- public static final class JapaneseDateCodec implements JsonCodec<JapaneseDate> {
+ public static final class JapaneseDateCodec implements JsonValueCodec<JapaneseDate> {
public static final JapaneseDateCodec INSTANCE = new JapaneseDateCodec();
@Override
@@ -2401,7 +2402,7 @@ public final class ScalarCodecs {
}
}
- public static final class MinguoDateCodec implements JsonCodec<MinguoDate> {
+ public static final class MinguoDateCodec implements JsonValueCodec<MinguoDate> {
public static final MinguoDateCodec INSTANCE = new MinguoDateCodec();
@Override
@@ -2462,7 +2463,7 @@ public final class ScalarCodecs {
}
}
- public static final class ThaiBuddhistDateCodec implements JsonCodec<ThaiBuddhistDate> {
+ public static final class ThaiBuddhistDateCodec implements JsonValueCodec<ThaiBuddhistDate> {
public static final ThaiBuddhistDateCodec INSTANCE = new ThaiBuddhistDateCodec();
@Override
@@ -2523,7 +2524,7 @@ public final class ScalarCodecs {
}
}
- public static final class AtomicBooleanCodec implements JsonCodec<AtomicBoolean> {
+ public static final class AtomicBooleanCodec implements JsonValueCodec<AtomicBoolean> {
public static final AtomicBooleanCodec INSTANCE = new AtomicBooleanCodec();
@Override
@@ -2560,7 +2561,7 @@ public final class ScalarCodecs {
}
}
- public static final class AtomicIntegerCodec implements JsonCodec<AtomicInteger> {
+ public static final class AtomicIntegerCodec implements JsonValueCodec<AtomicInteger> {
public static final AtomicIntegerCodec INSTANCE = new AtomicIntegerCodec();
@Override
@@ -2597,7 +2598,7 @@ public final class ScalarCodecs {
}
}
- public static final class AtomicLongCodec implements JsonCodec<AtomicLong> {
+ public static final class AtomicLongCodec implements JsonValueCodec<AtomicLong> {
public static final AtomicLongCodec INSTANCE = new AtomicLongCodec();
@Override
@@ -2634,12 +2635,17 @@ public final class ScalarCodecs {
}
}
- public static final class AtomicReferenceCodec implements JsonCodec<AtomicReference<?>> {
+ public static final class AtomicReferenceCodec implements JsonValueCodec<AtomicReference<?>> {
private final JsonTypeInfo valueTypeInfo;
public AtomicReferenceCodec(java.lang.reflect.Type valueType, JsonTypeResolver resolver) {
Class<?> valueRawType = CodecUtils.rawType(valueType, Object.class);
- valueTypeInfo = resolver.getTypeInfo(valueType, valueRawType);
+ this.valueTypeInfo = resolver.getTypeInfo(valueType, valueRawType);
+ }
+
+ @Internal
+ public AtomicReferenceCodec(JsonTypeInfo valueTypeInfo) {
+ this.valueTypeInfo = valueTypeInfo;
}
@Override
@@ -2685,7 +2691,7 @@ public final class ScalarCodecs {
}
}
- public static final class AtomicIntegerArrayCodec implements JsonCodec<AtomicIntegerArray> {
+ public static final class AtomicIntegerArrayCodec implements JsonValueCodec<AtomicIntegerArray> {
public static final AtomicIntegerArrayCodec INSTANCE = new AtomicIntegerArrayCodec();
@Override
@@ -2803,7 +2809,7 @@ public final class ScalarCodecs {
}
}
- public static final class AtomicLongArrayCodec implements JsonCodec<AtomicLongArray> {
+ public static final class AtomicLongArrayCodec implements JsonValueCodec<AtomicLongArray> {
public static final AtomicLongArrayCodec INSTANCE = new AtomicLongArrayCodec();
@Override
@@ -2922,12 +2928,17 @@ public final class ScalarCodecs {
}
public static final class AtomicReferenceArrayCodec
- implements JsonCodec<AtomicReferenceArray<?>> {
+ implements JsonValueCodec<AtomicReferenceArray<?>> {
private final JsonTypeInfo valueTypeInfo;
public AtomicReferenceArrayCodec(java.lang.reflect.Type valueType, JsonTypeResolver resolver) {
Class<?> valueRawType = CodecUtils.rawType(valueType, Object.class);
- valueTypeInfo = resolver.getTypeInfo(valueType, valueRawType);
+ this.valueTypeInfo = resolver.getTypeInfo(valueType, valueRawType);
+ }
+
+ @Internal
+ public AtomicReferenceArrayCodec(JsonTypeInfo valueTypeInfo) {
+ this.valueTypeInfo = valueTypeInfo;
}
@Override
@@ -3038,12 +3049,17 @@ public final class ScalarCodecs {
}
}
- public static final class OptionalCodec implements JsonCodec<Optional<?>> {
+ public static final class OptionalCodec implements JsonValueCodec<Optional<?>> {
private final JsonTypeInfo valueTypeInfo;
public OptionalCodec(java.lang.reflect.Type valueType, JsonTypeResolver resolver) {
Class<?> valueRawType = CodecUtils.rawType(valueType, Object.class);
- valueTypeInfo = resolver.getTypeInfo(valueType, valueRawType);
+ this.valueTypeInfo = resolver.getTypeInfo(valueType, valueRawType);
+ }
+
+ @Internal
+ public OptionalCodec(JsonTypeInfo valueTypeInfo) {
+ this.valueTypeInfo = valueTypeInfo;
}
@Override
@@ -3099,7 +3115,7 @@ public final class ScalarCodecs {
}
}
- public static final class OptionalIntCodec implements JsonCodec<OptionalInt> {
+ public static final class OptionalIntCodec implements JsonValueCodec<OptionalInt> {
public static final OptionalIntCodec INSTANCE = new OptionalIntCodec();
@Override
@@ -3146,7 +3162,7 @@ public final class ScalarCodecs {
}
}
- public static final class OptionalLongCodec implements JsonCodec<OptionalLong> {
+ public static final class OptionalLongCodec implements JsonValueCodec<OptionalLong> {
public static final OptionalLongCodec INSTANCE = new OptionalLongCodec();
@Override
@@ -3193,7 +3209,7 @@ public final class ScalarCodecs {
}
}
- public static final class OptionalDoubleCodec implements JsonCodec<OptionalDouble> {
+ public static final class OptionalDoubleCodec implements JsonValueCodec<OptionalDouble> {
public static final OptionalDoubleCodec INSTANCE = new OptionalDoubleCodec();
@Override
@@ -3246,7 +3262,7 @@ public final class ScalarCodecs {
}
}
- public static final class ByteBufferCodec implements JsonCodec<ByteBuffer> {
+ public static final class ByteBufferCodec implements JsonValueCodec<ByteBuffer> {
public static final ByteBufferCodec INSTANCE = new ByteBufferCodec();
@Override
@@ -3363,7 +3379,7 @@ public final class ScalarCodecs {
}
}
- public static final class EnumCodec implements JsonCodec<Enum<?>> {
+ public static final class EnumCodec implements JsonValueCodec<Enum<?>> {
private final Class<?> type;
private final long[] nameHashes;
private final long[] tokenPrefixes;
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/SqlJsonCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/SqlJsonCodecs.java
index d9b70cc57..3344aacba 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/codec/SqlJsonCodecs.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/SqlJsonCodecs.java
@@ -43,13 +43,14 @@ public final class SqlJsonCodecs {
private SqlJsonCodecs() {}
- public static void register(IdentityHashMap<Class<?>, JsonCodec<?>> codecs) {
+ public static void register(IdentityHashMap<Class<?>, JsonValueCodec<?>> codecs) {
register(codecs, SQL_DATE);
register(codecs, SQL_TIME);
register(codecs, SQL_TIMESTAMP);
}
- private static void register(IdentityHashMap<Class<?>, JsonCodec<?>> codecs, String className) {
+ private static void register(
+ IdentityHashMap<Class<?>, JsonValueCodec<?>> codecs, String className) {
Class<? extends Date> type = loadClass(className);
if (type != null) {
codecs.put(type, new SqlMillisCodec<>(type));
@@ -65,7 +66,7 @@ public final class SqlJsonCodecs {
}
}
- private static final class SqlMillisCodec<T extends Date> implements JsonCodec<T> {
+ private static final class SqlMillisCodec<T extends Date> implements JsonValueCodec<T> {
private final Constructor<T> constructor;
private SqlMillisCodec(Class<T> type) {
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonCodegen.java b/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonCodegen.java
index adebf9660..78f94542d 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonCodegen.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonCodegen.java
@@ -325,6 +325,9 @@ public final class JsonCodegen {
}
Class<?> stringWriterFieldType(JsonTypeInfo typeInfo) {
+ if (typeInfo.usesAnnotationCodec()) {
+ return StringWriterCodec.class;
+ }
if (typeInfo.usesDefaultObjectCodec()) {
return StringWriterCodec.class;
}
@@ -337,6 +340,9 @@ public final class JsonCodegen {
}
Class<?> utf8WriterFieldType(JsonTypeInfo typeInfo) {
+ if (typeInfo.usesAnnotationCodec()) {
+ return Utf8WriterCodec.class;
+ }
if (typeInfo.usesDefaultObjectCodec()) {
return Utf8WriterCodec.class;
}
@@ -349,6 +355,9 @@ public final class JsonCodegen {
}
Class<?> latin1ReaderFieldType(JsonTypeInfo typeInfo) {
+ if (typeInfo.usesAnnotationCodec()) {
+ return Latin1ReaderCodec.class;
+ }
if (typeInfo.usesDefaultObjectCodec()) {
return Latin1ReaderCodec.class;
}
@@ -360,6 +369,9 @@ public final class JsonCodegen {
}
Class<?> utf16ReaderFieldType(JsonTypeInfo typeInfo) {
+ if (typeInfo.usesAnnotationCodec()) {
+ return Utf16ReaderCodec.class;
+ }
if (typeInfo.usesDefaultObjectCodec()) {
return Utf16ReaderCodec.class;
}
@@ -371,6 +383,9 @@ public final class JsonCodegen {
}
Class<?> utf8ReaderFieldType(JsonTypeInfo typeInfo) {
+ if (typeInfo.usesAnnotationCodec()) {
+ return Utf8ReaderCodec.class;
+ }
if (typeInfo.usesDefaultObjectCodec()) {
return Utf8ReaderCodec.class;
}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java
index 28062ed2c..c611021ef 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java
@@ -36,14 +36,17 @@ public final class JsonCreatorFieldInfo {
private final int argumentIndex;
private final Type type;
private final Class<?> rawType;
+ private final JsonTypeUse typeUse;
private JsonTypeInfo typeInfo;
- public JsonCreatorFieldInfo(String name, int argumentIndex, Type type, Class<?> rawType) {
+ public JsonCreatorFieldInfo(
+ String name, int argumentIndex, Type type, Class<?> rawType, JsonTypeUse typeUse) {
this.name = name;
nameHash = JsonFieldNameHash.hash(name);
this.argumentIndex = argumentIndex;
this.type = type;
this.rawType = rawType;
+ this.typeUse = typeUse;
}
public String name() {
@@ -71,7 +74,8 @@ public final class JsonCreatorFieldInfo {
}
public void resolveType(JsonTypeResolver resolver) {
- typeInfo = resolver.getTypeInfo(type, rawType);
+ typeInfo =
+ typeUse == null ? resolver.getTypeInfo(type, rawType) : resolver.getTypeInfo(typeUse);
}
public Object readLatin1(Latin1JsonReader reader) {
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonFieldInfo.java b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonFieldInfo.java
index 270413fab..d4e1567c2 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonFieldInfo.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonFieldInfo.java
@@ -83,6 +83,7 @@ public final class JsonFieldInfo {
private final Class<?> writeRawType;
private final Type readType;
private final Class<?> readRawType;
+ private final JsonTypeUse typeUse;
private JsonFieldKind writeKind;
private JsonFieldKind readKind;
private int writeKindId;
@@ -138,7 +139,8 @@ public final class JsonFieldInfo {
Method readSetter,
JsonFieldAccessor writeAccessor,
JsonFieldAccessor readAccessor,
- TypeRef<?> ownerType) {
+ TypeRef<?> ownerType,
+ JsonTypeUse typeUse) {
this.name = name;
// The write-null decision and read index are both immutable after ObjectCodec construction.
// Packing the flag into the unused sign bit keeps JsonFieldInfo at its established object size
@@ -156,6 +158,7 @@ public final class JsonFieldInfo {
this.writeRawType = semanticRawType(writeType, writeFallback);
this.readType = resolveType(ownerType, readType(readField, readSetter));
this.readRawType = semanticRawType(readType, readFallback);
+ this.typeUse = typeUse;
this.writeAccessor = writeAccessor;
this.readAccessor = readAccessor;
writeKind = writeRawType == null ? null : kind(writeRawType);
@@ -343,13 +346,20 @@ public final class JsonFieldInfo {
}
public void resolveTypes(JsonTypeResolver typeResolver) {
+ JsonTypeInfo resolvedTypeInfo = typeUse == null ? null : typeResolver.getTypeInfo(typeUse);
if (writeRawType != null) {
- writeTypeInfo = typeResolver.getTypeInfo(writeType, writeRawType);
+ writeTypeInfo =
+ resolvedTypeInfo == null
+ ? typeResolver.getTypeInfo(writeType, writeRawType)
+ : resolvedTypeInfo;
writeKind = writeTypeInfo.kind();
writeKindId = kindId(writeKind);
}
if (readRawType != null) {
- readTypeInfo = typeResolver.getTypeInfo(readType, readRawType);
+ readTypeInfo =
+ resolvedTypeInfo == null
+ ? typeResolver.getTypeInfo(readType, readRawType)
+ : resolvedTypeInfo;
readKind = readTypeInfo.kind();
readPrimitiveKindId = primitiveKindId(readRawType, readKind);
}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonTypeUse.java b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonTypeUse.java
new file mode 100644
index 000000000..886350562
--- /dev/null
+++ b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonTypeUse.java
@@ -0,0 +1,934 @@
+/*
+ * 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.meta;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.GenericArrayType;
+import java.lang.reflect.Method;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+import java.lang.reflect.WildcardType;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import org.apache.fory.annotation.Internal;
+import org.apache.fory.json.ForyJsonException;
+import org.apache.fory.json.annotation.JsonCodec;
+import org.apache.fory.json.codec.JsonValueCodec;
+import org.apache.fory.platform.AndroidSupport;
+import org.apache.fory.platform.GraalvmSupport;
+import org.apache.fory.reflect.TypeRef;
+import org.apache.fory.reflect.TypeUseMetadata;
+import org.apache.fory.type.TypeUtils;
+import org.apache.fory.util.record.RecordComponent;
+
+/**
+ * Immutable cold metadata for source-explicit {@link JsonCodec} annotations on one Java type use.
+ *
+ * <p>Declaration annotations are intentionally absent. They remain lazy defaults of a raw target
+ * class and are resolved only when a value owner delegates to that node. Instances are retained
+ * only when the complete occurrence tree contains an explicit codec annotation.
+ */
+@Internal
+public final class JsonTypeUse {
+ private static final JsonTypeUse[] NO_CHILDREN = new JsonTypeUse[0];
+ private static final String[] NO_SOURCES = new String[0];
+ private static final boolean ANNOTATIONS_SUPPORTED =
+ !AndroidSupport.IS_ANDROID && !GraalvmSupport.IN_GRAALVM_NATIVE_IMAGE;
+
+ private final Type type;
+ private final Class<?> rawType;
+ private final Class<? extends JsonValueCodec<?>> codecClass;
+ private final String[] codecSources;
+ private final JsonTypeUse[] arguments;
+ private final JsonTypeUse arrayComponent;
+ private final JsonTypeUse[] upperBounds;
+ private final JsonTypeUse[] lowerBounds;
+ private final boolean hasExplicitCodec;
+ private final int hashCode;
+
+ private JsonTypeUse(
+ Type type,
+ Class<? extends JsonValueCodec<?>> codecClass,
+ String[] codecSources,
+ JsonTypeUse[] arguments,
+ JsonTypeUse arrayComponent,
+ JsonTypeUse[] upperBounds,
+ JsonTypeUse[] lowerBounds) {
+ this.type = type;
+ rawType = TypeUtils.getRawType(type);
+ this.codecClass = codecClass;
+ this.codecSources = emptyIfNull(codecSources);
+ this.arguments = emptyIfNull(arguments);
+ this.arrayComponent = arrayComponent;
+ this.upperBounds = emptyIfNull(upperBounds);
+ this.lowerBounds = emptyIfNull(lowerBounds);
+ hasExplicitCodec =
+ codecClass != null
+ || containsExplicit(this.arguments)
+ || (arrayComponent != null && arrayComponent.hasExplicitCodec)
+ || containsExplicit(this.upperBounds)
+ || containsExplicit(this.lowerBounds);
+ hashCode = structuralHashCode();
+ }
+
+ /** Returns whether JSON codec annotations are supported on the current platform. */
+ public static boolean annotationsSupported() {
+ return ANNOTATIONS_SUPPORTED;
+ }
+
+ /** Returns the explicit type-use tree for {@code field}, or {@code null} when none is present. */
+ public static JsonTypeUse forField(Field field) {
+ if (!ANNOTATIONS_SUPPORTED) {
+ return null;
+ }
+ return fromTypeUse(
+ TypeUseMetadata.fieldTypeUse(field),
+ "field " + field.getDeclaringClass().getName() + "." + field.getName());
+ }
+
+ /** Returns the explicit return type-use tree for {@code method}, or {@code null}. */
+ public static JsonTypeUse forMethodReturn(Method method) {
+ if (!ANNOTATIONS_SUPPORTED) {
+ return null;
+ }
+ return fromTypeUse(
+ TypeUseMetadata.methodReturnTypeUse(method),
+ "method return " + method.getDeclaringClass().getName() + "#" + method.getName());
+ }
+
+ /** Returns one explicit method-parameter type-use tree, or {@code null}. */
+ public static JsonTypeUse forMethodParameter(Method method, int parameterIndex) {
+ if (!ANNOTATIONS_SUPPORTED) {
+ checkParameterIndex(null, method.getParameterCount(), parameterIndex, method.toString());
+ return null;
+ }
+ Object[] parameters = TypeUseMetadata.methodParameterTypeUses(method);
+ checkParameterIndex(parameters, method.getParameterCount(), parameterIndex, method.toString());
+ return fromTypeUse(
+ parameters == null ? null : parameters[parameterIndex],
+ "method parameter "
+ + method.getDeclaringClass().getName()
+ + "#"
+ + method.getName()
+ + "["
+ + parameterIndex
+ + "]");
+ }
+
+ /** Returns one explicit constructor-parameter type-use tree, or {@code null}. */
+ public static JsonTypeUse forConstructorParameter(
+ Constructor<?> constructor, int parameterIndex) {
+ if (!ANNOTATIONS_SUPPORTED) {
+ checkParameterIndex(
+ null, constructor.getParameterCount(), parameterIndex, constructor.toString());
+ return null;
+ }
+ Object[] parameters = TypeUseMetadata.constructorParameterTypeUses(constructor);
+ checkParameterIndex(
+ parameters, constructor.getParameterCount(), parameterIndex, constructor.toString());
+ return fromTypeUse(
+ parameters == null ? null : parameters[parameterIndex],
+ "constructor parameter "
+ + constructor.getDeclaringClass().getName()
+ + "["
+ + parameterIndex
+ + "]");
+ }
+
+ /** Returns the explicit type-use tree for {@code component}, or {@code null}. */
+ public static JsonTypeUse forRecordComponent(RecordComponent component) {
+ if (!ANNOTATIONS_SUPPORTED) {
+ return null;
+ }
+ return fromTypeUse(
+ TypeUseMetadata.recordComponentTypeUse(component),
+ "record component " + component.getDeclaringRecord().getName() + "." + component.getName());
+ }
+
+ /**
+ * Builds an explicit tree from a platform-neutral type-use handle.
+ *
+ * <p>The returned value is {@code null} when annotation support is disabled or no codec occurs at
+ * any node. {@code source} identifies the field, accessor, record component, or creator parameter
+ * in diagnostics.
+ */
+ public static JsonTypeUse fromTypeUse(Object typeUse, String source) {
+ if (!ANNOTATIONS_SUPPORTED || typeUse == null) {
+ return null;
+ }
+ if (!scanExplicit(typeUse, source, "$")) {
+ return null;
+ }
+ return buildTypeUse(typeUse, source, "$");
+ }
+
+ /**
+ * Resolves one declared member type and its explicit tree against its parameterized owner.
+ *
+ * <p>{@code declaredTypeUse} may be {@code null}. A temporary unannotated skeleton is then used
+ * so an annotation supplied by an owner binding, such as {@code Envelope<@JsonCodec Money>}, is
+ * still substituted into an unannotated member declared as {@code T}. The result is {@code null}
+ * only when no explicit annotation survives substitution.
+ */
+ public static JsonTypeUse resolveMember(
+ TypeRef<?> ownerType,
+ JsonTypeUse annotatedOwner,
+ Type declaredType,
+ JsonTypeUse declaredTypeUse,
+ String path) {
+ JsonTypeUse declared =
+ declaredTypeUse == null
+ ? plainType(declaredType)
+ : requireType(declaredTypeUse, declaredType);
+ JsonTypeUse owner =
+ annotatedOwner == null
+ ? plainType(ownerType.getType())
+ : requireOwner(annotatedOwner, ownerType);
+ Map<TypeVariable<?>, JsonTypeUse> bindings = buildBindings(owner, path + ".owner");
+ JsonTypeUse resolved = resolveNode(declared, ownerType, bindings, path);
+ return resolved.hasExplicitCodec ? resolved : null;
+ }
+
+ /** Merges two already-resolved logical-property trees using exact-node codec semantics. */
+ public static JsonTypeUse merge(JsonTypeUse left, JsonTypeUse right, String path) {
+ if (left == null) {
+ return right;
+ }
+ if (right == null) {
+ return left;
+ }
+ requireSameShape(left, right, path);
+ Class<? extends JsonValueCodec<?>> mergedCodec = left.codecClass;
+ String[] mergedSources = left.codecSources;
+ if (mergedCodec == null) {
+ mergedCodec = right.codecClass;
+ mergedSources = right.codecSources;
+ } else if (right.codecClass != null) {
+ if (mergedCodec != right.codecClass) {
+ throw codecConflict(path, left, right);
+ }
+ mergedSources = mergeSources(left.codecSources, right.codecSources);
+ }
+ JsonTypeUse[] mergedArguments =
+ mergeChildren(left.arguments, right.arguments, path, ".argument[");
+ JsonTypeUse mergedComponent =
+ merge(left.arrayComponent, right.arrayComponent, path + ".component");
+ JsonTypeUse[] mergedUpper =
+ mergeChildren(left.upperBounds, right.upperBounds, path, ".upperBound[");
+ JsonTypeUse[] mergedLower =
+ mergeChildren(left.lowerBounds, right.lowerBounds, path, ".lowerBound[");
+ if (mergedCodec == left.codecClass
+ && mergedSources == left.codecSources
+ && mergedArguments == left.arguments
+ && mergedComponent == left.arrayComponent
+ && mergedUpper == left.upperBounds
+ && mergedLower == left.lowerBounds) {
+ return left;
+ }
+ return new JsonTypeUse(
+ left.type,
+ mergedCodec,
+ mergedSources,
+ mergedArguments,
+ mergedComponent,
+ mergedUpper,
+ mergedLower);
+ }
+
+ /**
+ * Projects this occurrence through its generic hierarchy to {@code targetRawType}.
+ *
+ * <p>Annotations on the concrete owner's arguments follow the matching type variables even when a
+ * collection or map subclass reorders its parameters. An explicit descendant that does not map to
+ * the target supertype is rejected because no target child can own it. The current root codec is
+ * not copied: it selects the concrete occurrence, not its supertype's value node.
+ */
+ public JsonTypeUse projectTo(Class<?> targetRawType, String path) {
+ if (!targetRawType.isAssignableFrom(rawType)) {
+ throw new ForyJsonException(
+ rawType.getTypeName() + " is not assignable to " + targetRawType.getTypeName());
+ }
+ Map<TypeVariable<?>, JsonTypeUse> bindings = buildBindings(this, path + ".owner");
+ TypeRef<?> projectedRef = supertype(TypeRef.of(type), targetRawType);
+ TypeVariable<?>[] parameters = targetRawType.getTypeParameters();
+ JsonTypeUse[] projectedArguments = new JsonTypeUse[parameters.length];
+ Type[] ordinaryArguments = typeArguments(projectedRef.getType());
+ for (int i = 0; i < parameters.length; i++) {
+ JsonTypeUse binding = bindings.get(parameters[i]);
+ if (binding == null) {
+ Type ordinary = i < ordinaryArguments.length ? ordinaryArguments[i] : parameters[i];
+ binding = plainType(ordinary);
+ }
+ projectedArguments[i] = binding;
+ }
+ JsonTypeUse projected =
+ new JsonTypeUse(
+ projectedRef.getType(),
+ null,
+ NO_SOURCES,
+ projectedArguments,
+ null,
+ NO_CHILDREN,
+ NO_CHILDREN);
+ rejectUnprojectedDescendants(projected, path, targetRawType);
+ return projected;
+ }
+
+ /** Rejects an explicit codec anywhere in this subtree for a non-value position. */
+ public void rejectExplicit(String position) {
+ JsonTypeUse explicit = firstExplicit();
+ if (explicit != null) {
+ throw new ForyJsonException(
+ "@JsonCodec from "
+ + explicit.codecSource()
+ + " cannot be used in "
+ + position
+ + " ("
+ + explicit.type.getTypeName()
+ + ")");
+ }
+ }
+
+ /** Rejects an explicit codec in a map-key subtree. */
+ public void rejectMapKey(String path) {
+ rejectExplicit("map-key subtree " + path + "; map keys are owned by MapKeyCodec");
+ }
+
+ /** Rejects a source-explicit child hidden by a complete codec at this node. */
+ public void rejectExplicitDescendants(String owner) {
+ JsonTypeUse descendant = firstExplicitDescendant();
+ if (descendant != null) {
+ throw new ForyJsonException(
+ "Complete JSON codec for "
+ + owner
+ + " hides descendant @JsonCodec from "
+ + descendant.codecSource());
+ }
+ }
+
+ public Type type() {
+ return type;
+ }
+
+ public Class<?> rawType() {
+ return rawType;
+ }
+
+ /** Returns the codec selected at this exact node, or {@code null}. */
+ public Class<? extends JsonValueCodec<?>> codecClass() {
+ return codecClass;
+ }
+
+ /** Returns one deterministic source for the codec at this node, or {@code null}. */
+ public String codecSource() {
+ return codecSources.length == 0 ? null : codecSources[0];
+ }
+
+ /** Returns all logical-property sources merged at this exact node. */
+ public String[] codecSources() {
+ return codecSources.clone();
+ }
+
+ /** Returns whether this exact occurrence node has a source-explicit codec. */
+ public boolean hasCodec() {
+ return codecClass != null;
+ }
+
+ /** Returns whether this node or any structurally nested node has an explicit codec. */
+ public boolean hasExplicitCodec() {
+ return hasExplicitCodec;
+ }
+
+ /** Returns whether a child below this node has an explicit codec. */
+ public boolean hasExplicitDescendant() {
+ return firstExplicitDescendant() != null;
+ }
+
+ /** Returns the first explicit child below this node in structural order, or {@code null}. */
+ public JsonTypeUse firstExplicitDescendant() {
+ JsonTypeUse explicit = firstExplicit(arguments);
+ if (explicit != null) {
+ return explicit;
+ }
+ if (arrayComponent != null) {
+ explicit = arrayComponent.firstExplicit();
+ if (explicit != null) {
+ return explicit;
+ }
+ }
+ explicit = firstExplicit(upperBounds);
+ return explicit == null ? firstExplicit(lowerBounds) : explicit;
+ }
+
+ public int argumentCount() {
+ return arguments.length;
+ }
+
+ public JsonTypeUse argument(int index) {
+ return arguments[index];
+ }
+
+ public JsonTypeUse arrayComponent() {
+ return arrayComponent;
+ }
+
+ public int upperBoundCount() {
+ return upperBounds.length;
+ }
+
+ public JsonTypeUse upperBound(int index) {
+ return upperBounds[index];
+ }
+
+ public int lowerBoundCount() {
+ return lowerBounds.length;
+ }
+
+ public JsonTypeUse lowerBound(int index) {
+ return lowerBounds[index];
+ }
+
+ @Override
+ public boolean equals(Object object) {
+ if (object == this) {
+ return true;
+ }
+ if (!(object instanceof JsonTypeUse)) {
+ return false;
+ }
+ JsonTypeUse other = (JsonTypeUse) object;
+ return type.equals(other.type)
+ && codecClass == other.codecClass
+ && Arrays.equals(arguments, other.arguments)
+ && Objects.equals(arrayComponent, other.arrayComponent)
+ && Arrays.equals(upperBounds, other.upperBounds)
+ && Arrays.equals(lowerBounds, other.lowerBounds);
+ }
+
+ @Override
+ public int hashCode() {
+ return hashCode;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder(type.getTypeName());
+ if (codecClass != null) {
+ builder.append(" @JsonCodec(").append(codecClass.getName()).append(')');
+ }
+ return builder.toString();
+ }
+
+ private static JsonTypeUse requireType(JsonTypeUse typeUse, Type expectedType) {
+ if (!typeUse.type.equals(expectedType)) {
+ throw new ForyJsonException(
+ "Type-use metadata "
+ + typeUse.type.getTypeName()
+ + " does not match declared type "
+ + expectedType.getTypeName());
+ }
+ return typeUse;
+ }
+
+ private static JsonTypeUse requireOwner(JsonTypeUse owner, TypeRef<?> ownerType) {
+ Type expected = ownerType.getType();
+ if (!owner.type.equals(expected)) {
+ throw new ForyJsonException(
+ "Annotated owner "
+ + owner.type.getTypeName()
+ + " does not match resolved owner "
+ + expected.getTypeName());
+ }
+ return owner;
+ }
+
+ private static boolean scanExplicit(Object typeUse, String source, String path) {
+ JsonCodec annotation = TypeUseMetadata.typeUseAnnotation(typeUse, JsonCodec.class);
+ Object[] upperBounds = TypeUseMetadata.wildcardUpperBounds(typeUse);
+ Object[] lowerBounds = TypeUseMetadata.wildcardLowerBounds(typeUse);
+ if (upperBounds != null || lowerBounds != null) {
+ boolean boundExplicit =
+ scanChildren(upperBounds, source, path, ".upperBound[")
+ | scanChildren(lowerBounds, source, path, ".lowerBound[");
+ if (annotation != null || boundExplicit) {
+ throw new ForyJsonException(
+ "@JsonCodec cannot target a wildcard or wildcard bound at " + source + " " + path);
+ }
+ return false;
+ }
+ boolean explicit = annotation != null;
+ explicit |= scanChildren(TypeUseMetadata.typeUseArguments(typeUse), source, path, ".argument[");
+ Object component = TypeUseMetadata.arrayComponentTypeUse(typeUse);
+ if (component != null) {
+ explicit |= scanExplicit(component, source, path + ".component");
+ }
+ return explicit;
+ }
+
+ private static boolean scanChildren(
+ Object[] children, String source, String path, String childPath) {
+ boolean explicit = false;
+ if (children != null) {
+ for (int i = 0; i < children.length; i++) {
+ explicit |= scanExplicit(children[i], source, path + childPath + i + "]");
+ }
+ }
+ return explicit;
+ }
+
+ private static JsonTypeUse buildTypeUse(Object typeUse, String source, String path) {
+ Type type = TypeUseMetadata.typeRef(typeUse).getType();
+ JsonCodec annotation = TypeUseMetadata.typeUseAnnotation(typeUse, JsonCodec.class);
+ Object[] argumentUses = TypeUseMetadata.typeUseArguments(typeUse);
+ JsonTypeUse[] arguments = buildTypeUseChildren(argumentUses, source, path, ".argument[");
+ if (arguments.length == 0 && type instanceof ParameterizedType) {
+ arguments = plainTypes(((ParameterizedType) type).getActualTypeArguments());
+ }
+ Object componentUse = TypeUseMetadata.arrayComponentTypeUse(typeUse);
+ JsonTypeUse component =
+ componentUse == null
+ ? plainArrayComponent(type)
+ : buildTypeUse(componentUse, source, path + ".component");
+ Object[] upperUses = TypeUseMetadata.wildcardUpperBounds(typeUse);
+ Object[] lowerUses = TypeUseMetadata.wildcardLowerBounds(typeUse);
+ JsonTypeUse[] upper = buildTypeUseChildren(upperUses, source, path, ".upperBound[");
+ JsonTypeUse[] lower = buildTypeUseChildren(lowerUses, source, path, ".lowerBound[");
+ if (upper.length == 0 && type instanceof WildcardType) {
+ upper = plainTypes(((WildcardType) type).getUpperBounds());
+ }
+ if (lower.length == 0 && type instanceof WildcardType) {
+ lower = plainTypes(((WildcardType) type).getLowerBounds());
+ }
+ return new JsonTypeUse(
+ type,
+ annotation == null ? null : readCodecClass(annotation, source, path),
+ annotation == null ? NO_SOURCES : new String[] {source + " at " + path},
+ arguments,
+ component,
+ upper,
+ lower);
+ }
+
+ private static Class<? extends JsonValueCodec<?>> readCodecClass(
+ JsonCodec annotation, String source, String path) {
+ try {
+ return annotation.value();
+ } catch (RuntimeException | LinkageError e) {
+ throw new ForyJsonException("Cannot resolve @JsonCodec at " + source + " " + path, e);
+ }
+ }
+
+ private static JsonTypeUse[] buildTypeUseChildren(
+ Object[] children, String source, String path, String childPath) {
+ if (children == null || children.length == 0) {
+ return NO_CHILDREN;
+ }
+ JsonTypeUse[] values = new JsonTypeUse[children.length];
+ for (int i = 0; i < children.length; i++) {
+ values[i] = buildTypeUse(children[i], source, path + childPath + i + "]");
+ }
+ return values;
+ }
+
+ private static JsonTypeUse plainType(Type type) {
+ JsonTypeUse[] arguments = NO_CHILDREN;
+ JsonTypeUse component = null;
+ JsonTypeUse[] upper = NO_CHILDREN;
+ JsonTypeUse[] lower = NO_CHILDREN;
+ if (type instanceof ParameterizedType) {
+ arguments = plainTypes(((ParameterizedType) type).getActualTypeArguments());
+ } else if (type instanceof GenericArrayType) {
+ component = plainType(((GenericArrayType) type).getGenericComponentType());
+ } else if (type instanceof Class && ((Class<?>) type).isArray()) {
+ component = plainType(((Class<?>) type).getComponentType());
+ } else if (type instanceof WildcardType) {
+ WildcardType wildcard = (WildcardType) type;
+ upper = plainTypes(wildcard.getUpperBounds());
+ lower = plainTypes(wildcard.getLowerBounds());
+ }
+ return new JsonTypeUse(type, null, NO_SOURCES, arguments, component, upper, lower);
+ }
+
+ private static JsonTypeUse[] plainTypes(Type[] types) {
+ if (types == null || types.length == 0) {
+ return NO_CHILDREN;
+ }
+ JsonTypeUse[] values = new JsonTypeUse[types.length];
+ for (int i = 0; i < types.length; i++) {
+ values[i] = plainType(types[i]);
+ }
+ return values;
+ }
+
+ private static JsonTypeUse plainArrayComponent(Type type) {
+ if (type instanceof GenericArrayType) {
+ return plainType(((GenericArrayType) type).getGenericComponentType());
+ }
+ if (type instanceof Class && ((Class<?>) type).isArray()) {
+ return plainType(((Class<?>) type).getComponentType());
+ }
+ return null;
+ }
+
+ private static Map<TypeVariable<?>, JsonTypeUse> buildBindings(JsonTypeUse owner, String path) {
+ Map<TypeVariable<?>, JsonTypeUse> bindings = new HashMap<>();
+ populateBindings(owner, bindings, new HashSet<Class<?>>(), path);
+ return bindings;
+ }
+
+ private static void populateBindings(
+ JsonTypeUse current,
+ Map<TypeVariable<?>, JsonTypeUse> bindings,
+ Set<Class<?>> visited,
+ String path) {
+ Class<?> rawType = current.rawType;
+ TypeVariable<?>[] variables = rawType.getTypeParameters();
+ int bindingCount = Math.min(variables.length, current.arguments.length);
+ for (int i = 0; i < bindingCount; i++) {
+ TypeVariable<?> variable = variables[i];
+ JsonTypeUse old = bindings.get(variable);
+ JsonTypeUse value = current.arguments[i];
+ bindings.put(
+ variable,
+ old == null
+ ? value
+ : merge(old, value, path + ".typeParameter[" + variable.getName() + "]"));
+ }
+ if (!visited.add(rawType)) {
+ return;
+ }
+ TypeRef<?> context = TypeRef.of(current.type);
+ Type superclass = rawType.getGenericSuperclass();
+ if (superclass != null) {
+ JsonTypeUse resolved =
+ resolveNode(plainType(superclass), context, bindings, path + ".superclass");
+ populateBindings(resolved, bindings, visited, path + ".superclass");
+ }
+ Type[] interfaces = rawType.getGenericInterfaces();
+ for (int i = 0; i < interfaces.length; i++) {
+ JsonTypeUse resolved =
+ resolveNode(plainType(interfaces[i]), context, bindings, path + ".interface[" + i + "]");
+ populateBindings(resolved, bindings, visited, path + ".interface[" + i + "]");
+ }
+ }
+
+ private static JsonTypeUse resolveNode(
+ JsonTypeUse node,
+ TypeRef<?> context,
+ Map<TypeVariable<?>, JsonTypeUse> bindings,
+ String path) {
+ Type declaredType = node.type;
+ if (declaredType instanceof TypeVariable) {
+ JsonTypeUse binding = bindings.get(declaredType);
+ if (binding != null && !binding.type.equals(declaredType)) {
+ return mergeVariableOccurrence(binding, node, path);
+ }
+ Type resolvedType = context.resolveType(declaredType).getType();
+ JsonTypeUse resolved =
+ resolvedType.equals(declaredType)
+ ? node
+ : mergeVariableOccurrence(plainType(resolvedType), node, path);
+ requireConcreteCodecTarget(resolved, path);
+ return resolved;
+ }
+ Type resolvedType = context.resolveType(declaredType).getType();
+ JsonTypeUse[] arguments =
+ resolveChildren(node.arguments, context, bindings, path, ".argument[");
+ JsonTypeUse component =
+ node.arrayComponent == null
+ ? null
+ : resolveNode(node.arrayComponent, context, bindings, path + ".component");
+ JsonTypeUse[] upper =
+ resolveChildren(node.upperBounds, context, bindings, path, ".upperBound[");
+ JsonTypeUse[] lower =
+ resolveChildren(node.lowerBounds, context, bindings, path, ".lowerBound[");
+ JsonTypeUse resolved =
+ new JsonTypeUse(
+ resolvedType, node.codecClass, node.codecSources, arguments, component, upper, lower);
+ requireConcreteCodecTarget(resolved, path);
+ return resolved;
+ }
+
+ private static JsonTypeUse[] resolveChildren(
+ JsonTypeUse[] children,
+ TypeRef<?> context,
+ Map<TypeVariable<?>, JsonTypeUse> bindings,
+ String path,
+ String childPath) {
+ if (children.length == 0) {
+ return children;
+ }
+ JsonTypeUse[] resolved = new JsonTypeUse[children.length];
+ for (int i = 0; i < children.length; i++) {
+ resolved[i] = resolveNode(children[i], context, bindings, path + childPath + i + "]");
+ }
+ return resolved;
+ }
+
+ private static JsonTypeUse mergeVariableOccurrence(
+ JsonTypeUse binding, JsonTypeUse occurrence, String path) {
+ if (occurrence.codecClass == null) {
+ return binding;
+ }
+ Class<? extends JsonValueCodec<?>> codec = binding.codecClass;
+ String[] sources = binding.codecSources;
+ if (codec == null) {
+ codec = occurrence.codecClass;
+ sources = occurrence.codecSources;
+ } else if (codec != occurrence.codecClass) {
+ throw codecConflict(path, binding, occurrence);
+ } else {
+ sources = mergeSources(binding.codecSources, occurrence.codecSources);
+ }
+ JsonTypeUse resolved =
+ new JsonTypeUse(
+ binding.type,
+ codec,
+ sources,
+ binding.arguments,
+ binding.arrayComponent,
+ binding.upperBounds,
+ binding.lowerBounds);
+ requireConcreteCodecTarget(resolved, path);
+ return resolved;
+ }
+
+ private static void requireConcreteCodecTarget(JsonTypeUse node, String path) {
+ if (node.codecClass != null
+ && (node.type instanceof TypeVariable || node.type instanceof WildcardType)) {
+ throw new ForyJsonException(
+ "@JsonCodec from "
+ + node.codecSource()
+ + " does not resolve to one concrete target at "
+ + path
+ + ": "
+ + node.type.getTypeName());
+ }
+ }
+
+ private void rejectUnprojectedDescendants(
+ JsonTypeUse projected, String path, Class<?> targetRawType) {
+ Set<String> projectedSources = new HashSet<>();
+ collectSources(projected, projectedSources, true);
+ Set<String> descendantSources = new LinkedHashSet<>();
+ for (JsonTypeUse argument : arguments) {
+ collectSources(argument, descendantSources, true);
+ }
+ if (arrayComponent != null) {
+ collectSources(arrayComponent, descendantSources, true);
+ }
+ for (String source : descendantSources) {
+ if (!projectedSources.contains(source)) {
+ throw new ForyJsonException(
+ "@JsonCodec from "
+ + source
+ + " does not map to a delegated "
+ + targetRawType.getTypeName()
+ + " child at "
+ + path);
+ }
+ }
+ }
+
+ private static void collectSources(
+ JsonTypeUse node, Set<String> sources, boolean includeCurrent) {
+ if (includeCurrent) {
+ sources.addAll(Arrays.asList(node.codecSources));
+ }
+ for (JsonTypeUse argument : node.arguments) {
+ collectSources(argument, sources, true);
+ }
+ if (node.arrayComponent != null) {
+ collectSources(node.arrayComponent, sources, true);
+ }
+ for (JsonTypeUse bound : node.upperBounds) {
+ collectSources(bound, sources, true);
+ }
+ for (JsonTypeUse bound : node.lowerBounds) {
+ collectSources(bound, sources, true);
+ }
+ }
+
+ private static JsonTypeUse[] mergeChildren(
+ JsonTypeUse[] left, JsonTypeUse[] right, String path, String childPath) {
+ if (left.length != right.length) {
+ throw incompatibleTrees(path, left.length, right.length);
+ }
+ JsonTypeUse[] merged = null;
+ for (int i = 0; i < left.length; i++) {
+ JsonTypeUse value = merge(left[i], right[i], path + childPath + i + "]");
+ if (value != left[i] && merged == null) {
+ merged = left.clone();
+ }
+ if (merged != null) {
+ merged[i] = value;
+ }
+ }
+ return merged == null ? left : merged;
+ }
+
+ private static void requireSameShape(JsonTypeUse left, JsonTypeUse right, String path) {
+ if (!left.type.equals(right.type)
+ || left.arguments.length != right.arguments.length
+ || (left.arrayComponent == null) != (right.arrayComponent == null)
+ || left.upperBounds.length != right.upperBounds.length
+ || left.lowerBounds.length != right.lowerBounds.length) {
+ throw new ForyJsonException(
+ "Cannot merge @JsonCodec metadata for unequal resolved types at "
+ + path
+ + ": "
+ + left.type.getTypeName()
+ + " and "
+ + right.type.getTypeName());
+ }
+ }
+
+ private static ForyJsonException codecConflict(String path, JsonTypeUse left, JsonTypeUse right) {
+ return new ForyJsonException(
+ "Conflicting @JsonCodec values at "
+ + path
+ + ": "
+ + left.codecClass.getName()
+ + " from "
+ + Arrays.toString(left.codecSources)
+ + " and "
+ + right.codecClass.getName()
+ + " from "
+ + Arrays.toString(right.codecSources));
+ }
+
+ private static ForyJsonException incompatibleTrees(String path, int left, int right) {
+ return new ForyJsonException(
+ "Cannot merge @JsonCodec metadata with different child counts at "
+ + path
+ + ": "
+ + left
+ + " and "
+ + right);
+ }
+
+ private static String[] mergeSources(String[] left, String[] right) {
+ boolean hasNewSource = false;
+ for (String source : right) {
+ if (!contains(left, source)) {
+ hasNewSource = true;
+ break;
+ }
+ }
+ if (!hasNewSource) {
+ return left;
+ }
+ String[] merged = Arrays.copyOf(left, left.length + right.length);
+ int size = left.length;
+ for (String source : right) {
+ if (!contains(merged, size, source)) {
+ merged[size++] = source;
+ }
+ }
+ return size == merged.length ? merged : Arrays.copyOf(merged, size);
+ }
+
+ private static boolean contains(String[] values, String value) {
+ return contains(values, values.length, value);
+ }
+
+ private static boolean contains(String[] values, int length, String value) {
+ for (int i = 0; i < length; i++) {
+ if (values[i].equals(value)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ private static TypeRef<?> supertype(TypeRef<?> typeRef, Class<?> rawType) {
+ return ((TypeRef) typeRef).getSupertype((Class) rawType);
+ }
+
+ private static Type[] typeArguments(Type type) {
+ return type instanceof ParameterizedType
+ ? ((ParameterizedType) type).getActualTypeArguments()
+ : new Type[0];
+ }
+
+ private static JsonTypeUse firstExplicit(JsonTypeUse[] children) {
+ for (JsonTypeUse child : children) {
+ JsonTypeUse explicit = child.firstExplicit();
+ if (explicit != null) {
+ return explicit;
+ }
+ }
+ return null;
+ }
+
+ private JsonTypeUse firstExplicit() {
+ return codecClass == null ? firstExplicitDescendant() : this;
+ }
+
+ private static boolean containsExplicit(JsonTypeUse[] children) {
+ for (JsonTypeUse child : children) {
+ if (child.hasExplicitCodec) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private int structuralHashCode() {
+ int hash = 31 * type.hashCode() + System.identityHashCode(codecClass);
+ hash = 31 * hash + Arrays.hashCode(arguments);
+ hash = 31 * hash + Objects.hashCode(arrayComponent);
+ hash = 31 * hash + Arrays.hashCode(upperBounds);
+ return 31 * hash + Arrays.hashCode(lowerBounds);
+ }
+
+ private static JsonTypeUse[] emptyIfNull(JsonTypeUse[] values) {
+ return values == null || values.length == 0 ? NO_CHILDREN : values;
+ }
+
+ private static String[] emptyIfNull(String[] values) {
+ return values == null || values.length == 0 ? NO_SOURCES : values;
+ }
+
+ private static void checkParameterIndex(
+ Object[] typeUses, int parameterCount, int parameterIndex, String executable) {
+ if (parameterIndex < 0 || parameterIndex >= parameterCount) {
+ throw new IndexOutOfBoundsException(
+ "Parameter index " + parameterIndex + " is outside " + executable);
+ }
+ if (typeUses != null && typeUses.length != parameterCount) {
+ throw new ForyJsonException(
+ "Incomplete type-use metadata for "
+ + executable
+ + ": expected "
+ + parameterCount
+ + " parameters but found "
+ + typeUses.length);
+ }
+ }
+}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/CodecRegistry.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/CodecRegistry.java
index 0ad0de269..14773aaed 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/CodecRegistry.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/CodecRegistry.java
@@ -25,11 +25,11 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
-import org.apache.fory.json.codec.JsonCodec;
+import org.apache.fory.json.codec.JsonValueCodec;
import org.apache.fory.util.Preconditions;
/**
- * Builder-side registry of exact user-supplied {@link JsonCodec} bindings.
+ * Builder-side registry of exact user-supplied {@link JsonValueCodec} bindings.
*
* <p>Registration is keyed by class identity and replaces any previous codec for the exact class. A
* {@link JsonSharedRegistry} receives a copy when a runtime is built, separating later builder
@@ -38,39 +38,39 @@ import org.apache.fory.util.Preconditions;
* code-generation naming state.
*/
public final class CodecRegistry {
- private final ConcurrentMap<Class<?>, JsonCodec<?>> codecs;
+ private final ConcurrentMap<Class<?>, JsonValueCodec<?>> codecs;
public CodecRegistry() {
codecs = new ConcurrentHashMap<>();
}
- private CodecRegistry(ConcurrentMap<Class<?>, JsonCodec<?>> codecs) {
+ private CodecRegistry(ConcurrentMap<Class<?>, JsonValueCodec<?>> codecs) {
this.codecs = codecs;
}
- public <T> void register(Class<T> type, JsonCodec<T> codec) {
+ public <T> void register(Class<T> type, JsonValueCodec<T> codec) {
Preconditions.checkNotNull(type);
Preconditions.checkNotNull(codec);
codecs.put(type, codec);
}
- public JsonCodec<?> get(Class<?> type) {
+ public JsonValueCodec<?> get(Class<?> type) {
return codecs.get(type);
}
public CodecRegistry copy() {
- ConcurrentMap<Class<?>, JsonCodec<?>> copied = new ConcurrentHashMap<>(codecs.size());
- for (Map.Entry<Class<?>, JsonCodec<?>> entry : codecs.entrySet()) {
+ ConcurrentMap<Class<?>, JsonValueCodec<?>> copied = new ConcurrentHashMap<>(codecs.size());
+ for (Map.Entry<Class<?>, JsonValueCodec<?>> entry : codecs.entrySet()) {
copied.put(entry.getKey(), entry.getValue());
}
return new CodecRegistry(copied);
}
public String codegenKey() {
- List<Map.Entry<Class<?>, JsonCodec<?>>> entries = new ArrayList<>(codecs.entrySet());
+ List<Map.Entry<Class<?>, JsonValueCodec<?>>> entries = new ArrayList<>(codecs.entrySet());
entries.sort(Comparator.comparing(entry -> entry.getKey().getName()));
StringBuilder builder = new StringBuilder(entries.size() * 48);
- for (Map.Entry<Class<?>, JsonCodec<?>> entry : entries) {
+ for (Map.Entry<Class<?>, JsonValueCodec<?>> entry : entries) {
builder
.append(entry.getKey().getName())
.append('=')
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/InheritedJsonValueCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/InheritedJsonValueCodec.java
new file mode 100644
index 000000000..f1d487a53
--- /dev/null
+++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/InheritedJsonValueCodec.java
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.fory.json.resolver;
+
+import java.lang.reflect.Type;
+import org.apache.fory.json.ForyJsonException;
+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;
+
+/**
+ * Applies the runtime result contract when a broader declaration codec is inherited by a target.
+ */
+final class InheritedJsonValueCodec implements JsonValueCodec<Object> {
+ private final Type targetType;
+ private final Class<?> targetRawType;
+ private final Class<? extends JsonValueCodec<?>> codecClass;
+ private final String origins;
+ private final JsonValueCodec<Object> delegate;
+
+ InheritedJsonValueCodec(
+ Type targetType,
+ Class<?> targetRawType,
+ Class<? extends JsonValueCodec<?>> codecClass,
+ Class<?>[] origins,
+ JsonValueCodec<?> delegate) {
+ this.targetType = targetType;
+ this.targetRawType = targetRawType;
+ this.codecClass = codecClass;
+ this.origins = originNames(origins);
+ this.delegate = erase(delegate);
+ }
+
+ @Override
+ public void writeString(StringJsonWriter writer, Object value) {
+ delegate.writeString(writer, value);
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, Object value) {
+ delegate.writeUtf8(writer, value);
+ }
+
+ @Override
+ public Object readLatin1(Latin1JsonReader reader) {
+ return validate(delegate.readLatin1(reader));
+ }
+
+ @Override
+ public Object readUtf16(Utf16JsonReader reader) {
+ return validate(delegate.readUtf16(reader));
+ }
+
+ @Override
+ public Object readUtf8(Utf8JsonReader reader) {
+ return validate(delegate.readUtf8(reader));
+ }
+
+ private Object validate(Object value) {
+ if (value != null && !targetRawType.isInstance(value)) {
+ throw incompatibleResult(value.getClass());
+ }
+ return value;
+ }
+
+ private ForyJsonException incompatibleResult(Class<?> actualType) {
+ return new ForyJsonException(
+ "Json codec "
+ + codecClass.getName()
+ + " declared on "
+ + origins
+ + " returned "
+ + actualType.getName()
+ + " while decoding "
+ + targetType.getTypeName()
+ + " (raw type "
+ + targetRawType.getName()
+ + "); expected null or a value assignable to "
+ + targetRawType.getName()
+ + ".");
+ }
+
+ private static String originNames(Class<?>[] origins) {
+ StringBuilder builder = new StringBuilder();
+ for (int i = 0; i < origins.length; i++) {
+ if (i != 0) {
+ builder.append(", ");
+ }
+ builder.append(origins[i].getName());
+ }
+ return builder.toString();
+ }
+
+ @SuppressWarnings("unchecked")
+ private static JsonValueCodec<Object> erase(JsonValueCodec<?> codec) {
+ return (JsonValueCodec<Object>) codec;
+ }
+}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonCodecDeclaration.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonCodecDeclaration.java
new file mode 100644
index 000000000..565f9b190
--- /dev/null
+++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonCodecDeclaration.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.fory.json.resolver;
+
+import java.lang.reflect.Type;
+import org.apache.fory.json.codec.JsonValueCodec;
+
+/** Immutable result of resolving one direct or inherited {@code @JsonCodec} declaration. */
+final class JsonCodecDeclaration {
+ private final Class<? extends JsonValueCodec<?>> codecClass;
+ private final Class<?>[] origins;
+ private final boolean inherited;
+
+ JsonCodecDeclaration(
+ Class<? extends JsonValueCodec<?>> codecClass, Class<?>[] origins, boolean inherited) {
+ this.codecClass = codecClass;
+ this.origins = origins.clone();
+ this.inherited = inherited;
+ }
+
+ Class<? extends JsonValueCodec<?>> codecClass() {
+ return codecClass;
+ }
+
+ boolean inherited() {
+ return inherited;
+ }
+
+ JsonValueCodec<?> bind(Type targetType, Class<?> targetRawType, JsonValueCodec<?> codec) {
+ if (!inherited) {
+ return codec;
+ }
+ return new InheritedJsonValueCodec(targetType, targetRawType, codecClass, origins, codec);
+ }
+}
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 e0f4aa2ee..5256c236b 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,6 +20,8 @@
package org.apache.fory.json.resolver;
import java.io.File;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.BigInteger;
@@ -48,13 +50,19 @@ import java.time.chrono.HijrahDate;
import java.time.chrono.JapaneseDate;
import java.time.chrono.MinguoDate;
import java.time.chrono.ThaiBuddhistDate;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
import java.util.Currency;
import java.util.Date;
+import java.util.Deque;
import java.util.HashSet;
import java.util.IdentityHashMap;
+import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
@@ -80,20 +88,23 @@ import org.apache.fory.json.JsonConfig;
import org.apache.fory.json.JsonTypeCheckContext;
import org.apache.fory.json.JsonTypeChecker;
import org.apache.fory.json.PropertyNamingStrategy;
+import org.apache.fory.json.annotation.JsonCodec;
import org.apache.fory.json.annotation.JsonSubTypes;
import org.apache.fory.json.annotation.JsonSubTypes.Inclusion;
import org.apache.fory.json.codec.ArrayCodec;
import org.apache.fory.json.codec.CodecUtils;
import org.apache.fory.json.codec.CollectionCodec;
import org.apache.fory.json.codec.GuavaCodecs;
-import org.apache.fory.json.codec.JsonCodec;
import org.apache.fory.json.codec.JsonSubTypesInfo;
+import org.apache.fory.json.codec.JsonValueCodec;
import org.apache.fory.json.codec.MapCodec;
import org.apache.fory.json.codec.ScalarCodecs;
import org.apache.fory.json.codec.SqlJsonCodecs;
import org.apache.fory.json.codegen.JsonCodegen;
import org.apache.fory.json.codegen.JsonJITContext;
import org.apache.fory.json.meta.JsonFieldKind;
+import org.apache.fory.json.meta.JsonTypeUse;
+import org.apache.fory.platform.AndroidSupport;
import org.apache.fory.platform.GraalvmSupport;
import org.apache.fory.reflect.TypeRef;
import org.apache.fory.resolver.DisallowedList;
@@ -118,9 +129,22 @@ import org.apache.fory.type.TypeUtils;
*/
public final class JsonSharedRegistry {
private static final int TYPE_CHECK_CACHE_LIMIT = 8192;
+ private static final boolean CODEC_ANNOTATIONS_ENABLED =
+ !AndroidSupport.IS_ANDROID && !GraalvmSupport.IN_GRAALVM_NATIVE_IMAGE;
+ private static final Comparator<DeclarationCandidate> DECLARATION_ORDER =
+ new Comparator<DeclarationCandidate>() {
+ @Override
+ public int compare(DeclarationCandidate left, DeclarationCandidate right) {
+ int result = left.declarationType.getName().compareTo(right.declarationType.getName());
+ if (result != 0) {
+ return result;
+ }
+ return left.codecClass.getName().compareTo(right.codecClass.getName());
+ }
+ };
private final CodecRegistry customCodecs;
- private final IdentityHashMap<Class<?>, JsonCodec<?>> exactCodecs;
+ private final IdentityHashMap<Class<?>, JsonValueCodec<?>> exactCodecs;
private final JsonTypeChecker typeChecker;
private final JsonTypeCheckContext typeCheckContext;
private final ConcurrentHashMap<String, Boolean> typeCheckCache;
@@ -133,6 +157,10 @@ public final class JsonSharedRegistry {
private final boolean writeNullFields;
private final ClassLoader classLoader;
private final IdentityHashMap<Class<?>, JsonSubTypesInfo> subTypesCache;
+ private final IdentityHashMap<Class<?>, JsonCodecDeclaration> codecDeclarations;
+ private final Set<Class<?>> typesWithoutCodecDeclaration;
+ private final ConcurrentHashMap<Class<? extends JsonValueCodec<?>>, JsonValueCodec<?>>
+ annotationCodecs;
public JsonSharedRegistry(JsonConfig config) {
this(config, null);
@@ -150,6 +178,10 @@ public final class JsonSharedRegistry {
classLoader = config.classLoader();
exactCodecs = new IdentityHashMap<>();
subTypesCache = new IdentityHashMap<>();
+ codecDeclarations = new IdentityHashMap<>();
+ typesWithoutCodecDeclaration =
+ Collections.newSetFromMap(new IdentityHashMap<Class<?>, Boolean>());
+ annotationCodecs = new ConcurrentHashMap<>();
boolean codegenEnabled = config.codegenEnabled();
codegen = codegenEnabled ? new JsonCodegen(config.getCodegenHash(), classLoader) : null;
asyncCompilationEnabled = codegenEnabled && config.asyncCompilationEnabled();
@@ -157,13 +189,13 @@ public final class JsonSharedRegistry {
registerExactCodecs();
}
- public JsonCodec<?> createCodec(
+ public JsonValueCodec<?> createCodec(
Class<?> rawType, TypeRef<?> typeRef, JsonTypeResolver localResolver) {
- JsonCodec<?> customCodec = customCodecs.get(rawType);
+ JsonValueCodec<?> customCodec = customCodecs.get(rawType);
if (customCodec != null) {
return customCodec;
}
- JsonCodec<?> codec = exactCodecs.get(rawType);
+ JsonValueCodec<?> codec = exactCodecs.get(rawType);
if (codec != null) {
return codec;
}
@@ -226,6 +258,42 @@ public final class JsonSharedRegistry {
return null;
}
+ JsonValueCodec<?> createCodec(JsonTypeUse typeUse, JsonTypeResolver localResolver) {
+ Class<?> rawType = typeUse.rawType();
+ if (rawType.isArray()) {
+ JsonTypeUse component = typeUse.arrayComponent();
+ return ArrayCodec.create(rawType, localResolver.getTypeInfo(component));
+ }
+ if (rawType == Optional.class) {
+ return new ScalarCodecs.OptionalCodec(localResolver.getTypeInfo(typeUse.argument(0)));
+ }
+ if (rawType == AtomicReference.class) {
+ return new ScalarCodecs.AtomicReferenceCodec(localResolver.getTypeInfo(typeUse.argument(0)));
+ }
+ if (rawType == AtomicReferenceArray.class) {
+ return new ScalarCodecs.AtomicReferenceArrayCodec(
+ localResolver.getTypeInfo(typeUse.argument(0)));
+ }
+ if (Collection.class.isAssignableFrom(rawType)) {
+ JsonTypeUse collection = typeUse.projectTo(Collection.class, rawType.getTypeName());
+ JsonTypeUse element = collection.argument(0);
+ return CollectionCodec.create(rawType, element.rawType(), localResolver.getTypeInfo(element));
+ }
+ if (Map.class.isAssignableFrom(rawType)) {
+ JsonTypeUse map = typeUse.projectTo(Map.class, rawType.getTypeName());
+ JsonTypeUse key = map.argument(0);
+ key.rejectMapKey(rawType.getTypeName());
+ localResolver.checkMapKeySecure(key.rawType());
+ JsonTypeUse value = map.argument(1);
+ return MapCodec.create(rawType, key.rawType(), localResolver.getTypeInfo(value));
+ }
+ JsonValueCodec<?> codec = createCodec(rawType, TypeRef.of(typeUse.type()), localResolver);
+ if (codec != null) {
+ typeUse.rejectExplicitDescendants(rawType.getTypeName());
+ }
+ return codec;
+ }
+
public JsonFieldKind kind(Class<?> type) {
// A registered codec owns the full representation. Resolve that choice before object metadata
// and codegen specialize fields so generated and interpreted paths cannot bypass the codec.
@@ -298,8 +366,229 @@ public final class JsonSharedRegistry {
return classLoader;
}
- boolean hasCustomCodec(Class<?> type) {
- return customCodecs.get(type) != null;
+ JsonValueCodec<?> customCodec(Class<?> type) {
+ return customCodecs.get(type);
+ }
+
+ JsonCodecDeclaration codecDeclaration(Class<?> targetType) {
+ if (!CODEC_ANNOTATIONS_ENABLED || 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);
+ }
+ return resolved;
+ }
+ }
+
+ JsonValueCodec<?> annotationCodec(
+ Class<?> targetType, Class<? extends JsonValueCodec<?>> codecClass) {
+ checkCustomSecure(targetType);
+ return annotationCodecs.computeIfAbsent(codecClass, JsonSharedRegistry::newAnnotationCodec);
+ }
+
+ private JsonCodecDeclaration resolveCodecDeclaration(Class<?> targetType) {
+ DeclarationCandidate direct = declaredCodec(targetType);
+ if (direct != null) {
+ return new JsonCodecDeclaration(direct.codecClass, new Class<?>[] {targetType}, false);
+ }
+ List<DeclarationCandidate> candidates = inheritedCodecCandidates(targetType);
+ if (candidates.isEmpty()) {
+ return null;
+ }
+ List<DeclarationCandidate> frontier = mostSpecificDeclarations(candidates);
+ Collections.sort(frontier, DECLARATION_ORDER);
+ Class<? extends JsonValueCodec<?>> codecClass = frontier.get(0).codecClass;
+ for (int i = 1; i < frontier.size(); i++) {
+ if (frontier.get(i).codecClass != codecClass) {
+ throw inheritedCodecConflict(targetType, frontier);
+ }
+ }
+ Class<?>[] origins = new Class<?>[frontier.size()];
+ for (int i = 0; i < frontier.size(); i++) {
+ origins[i] = frontier.get(i).declarationType;
+ }
+ return new JsonCodecDeclaration(codecClass, origins, true);
+ }
+
+ private static List<DeclarationCandidate> inheritedCodecCandidates(Class<?> targetType) {
+ List<DeclarationCandidate> candidates = new ArrayList<>();
+ Set<Class<?>> visited = Collections.newSetFromMap(new IdentityHashMap<Class<?>, Boolean>());
+ Deque<Class<?>> pending = new ArrayDeque<>();
+ addParents(targetType, pending);
+ while (!pending.isEmpty()) {
+ Class<?> current = pending.removeFirst();
+ if (!visited.add(current)) {
+ continue;
+ }
+ if (!current.isAnnotation()) {
+ DeclarationCandidate candidate = declaredCodec(current);
+ if (candidate != null) {
+ candidates.add(candidate);
+ }
+ }
+ addParents(current, pending);
+ }
+ return candidates;
+ }
+
+ private static void addParents(Class<?> type, Deque<Class<?>> pending) {
+ Class<?> superclass = type.getSuperclass();
+ if (superclass != null) {
+ pending.addLast(superclass);
+ }
+ Class<?>[] interfaces = type.getInterfaces();
+ for (Class<?> interfaceType : interfaces) {
+ pending.addLast(interfaceType);
+ }
+ }
+
+ private static List<DeclarationCandidate> mostSpecificDeclarations(
+ List<DeclarationCandidate> candidates) {
+ List<DeclarationCandidate> frontier = new ArrayList<>(candidates.size());
+ for (DeclarationCandidate candidate : candidates) {
+ boolean dominated = false;
+ for (DeclarationCandidate other : candidates) {
+ if (candidate.declarationType != other.declarationType
+ && candidate.declarationType.isAssignableFrom(other.declarationType)) {
+ dominated = true;
+ break;
+ }
+ }
+ if (!dominated) {
+ frontier.add(candidate);
+ }
+ }
+ return frontier;
+ }
+
+ private static DeclarationCandidate declaredCodec(Class<?> declarationType) {
+ JsonCodec annotation;
+ try {
+ annotation = declarationType.getDeclaredAnnotation(JsonCodec.class);
+ } catch (RuntimeException | LinkageError e) {
+ throw new ForyJsonException(
+ "Cannot read @JsonCodec declared on " + declarationType.getName(), e);
+ }
+ if (annotation == null) {
+ return null;
+ }
+ try {
+ return new DeclarationCandidate(declarationType, annotation.value());
+ } catch (RuntimeException | LinkageError e) {
+ throw new ForyJsonException(
+ "Cannot resolve @JsonCodec declared on " + declarationType.getName(), e);
+ }
+ }
+
+ private static ForyJsonException inheritedCodecConflict(
+ Class<?> targetType, List<DeclarationCandidate> frontier) {
+ StringBuilder message =
+ new StringBuilder("Conflicting inherited @JsonCodec declarations for ")
+ .append(targetType.getName())
+ .append(':');
+ for (DeclarationCandidate candidate : frontier) {
+ message
+ .append(' ')
+ .append(candidate.declarationType.getName())
+ .append(" -> ")
+ .append(candidate.codecClass.getName())
+ .append(';');
+ }
+ message
+ .append(" declare @JsonCodec on ")
+ .append(targetType.getName())
+ .append(", annotate the current type use, or register an exact codec for ")
+ .append(targetType.getName())
+ .append(".");
+ return new ForyJsonException(message.toString());
+ }
+
+ private static JsonValueCodec<?> newAnnotationCodec(
+ Class<? extends JsonValueCodec<?>> codecClass) {
+ validateCodecClass(codecClass);
+ Constructor<? extends JsonValueCodec<?>> constructor;
+ try {
+ constructor = codecClass.getConstructor();
+ } catch (NoSuchMethodException e) {
+ throw invalidCodecClass(codecClass, "must have a public no-argument constructor", e);
+ } catch (SecurityException e) {
+ throw inaccessibleCodecClass(codecClass, e);
+ } catch (LinkageError e) {
+ throw invalidCodecClass(codecClass, "constructor cannot be inspected", e);
+ }
+ try {
+ return constructor.newInstance();
+ } catch (IllegalAccessException e) {
+ // A public constructor in an exported package is directly invocable. A package that is only
+ // opened to Fory requires access elevation; a closed package fails before application code
+ // can run.
+ try {
+ constructor.setAccessible(true);
+ return constructor.newInstance();
+ } catch (InvocationTargetException retryFailure) {
+ throw invalidCodecClass(codecClass, "constructor failed", retryFailure.getCause());
+ } catch (ReflectiveOperationException | LinkageError | RuntimeException retryFailure) {
+ throw inaccessibleCodecClass(codecClass, retryFailure);
+ }
+ } catch (InvocationTargetException e) {
+ throw invalidCodecClass(codecClass, "constructor failed", e.getCause());
+ } catch (ReflectiveOperationException | LinkageError e) {
+ throw invalidCodecClass(codecClass, "cannot be constructed", e);
+ } catch (RuntimeException e) {
+ throw invalidCodecClass(codecClass, "cannot be constructed", e);
+ }
+ }
+
+ private static void validateCodecClass(Class<? extends JsonValueCodec<?>> codecClass) {
+ int modifiers = codecClass.getModifiers();
+ if (!Modifier.isPublic(modifiers)) {
+ throw invalidCodecClass(codecClass, "must be public", null);
+ }
+ if (codecClass.isInterface() || Modifier.isAbstract(modifiers)) {
+ throw invalidCodecClass(codecClass, "must be concrete", null);
+ }
+ if (codecClass.getEnclosingClass() != null
+ && (!codecClass.isMemberClass() || !Modifier.isStatic(modifiers))) {
+ throw invalidCodecClass(codecClass, "must be top-level or a static nested class", null);
+ }
+ for (Class<?> enclosing = codecClass.getEnclosingClass();
+ enclosing != null;
+ enclosing = enclosing.getEnclosingClass()) {
+ if (!Modifier.isPublic(enclosing.getModifiers())) {
+ throw invalidCodecClass(codecClass, "must be enclosed only by public classes", null);
+ }
+ }
+ }
+
+ private static ForyJsonException inaccessibleCodecClass(
+ Class<? extends JsonValueCodec<?>> codecClass, Throwable cause) {
+ Package codecPackage = codecClass.getPackage();
+ String packageName = codecPackage == null ? "the unnamed package" : codecPackage.getName();
+ return new ForyJsonException(
+ "Cannot access the public no-argument constructor of JSON codec "
+ + codecClass.getName()
+ + "; export or open package "
+ + packageName
+ + " to module org.apache.fory.json.",
+ cause);
+ }
+
+ private static ForyJsonException invalidCodecClass(
+ Class<? extends JsonValueCodec<?>> codecClass, String reason, Throwable cause) {
+ String message = "JSON codec " + codecClass.getName() + ' ' + reason + '.';
+ return cause == null ? new ForyJsonException(message) : new ForyJsonException(message, cause);
}
JsonSubTypesInfo subTypesInfo(Class<?> baseType) {
@@ -485,7 +774,20 @@ public final class JsonSharedRegistry {
}
void checkSecure(Class<?> type) {
- if (!isSecureType(type)) {
+ boolean secure = customCodecs.get(type) == null ? isSecureType(type) : isCustomSecureType(type);
+ if (!secure) {
+ throw forbiddenClass(type.getName());
+ }
+ }
+
+ void checkCustomSecure(Class<?> type) {
+ if (!isCustomSecureType(type)) {
+ throw forbiddenClass(type.getName());
+ }
+ }
+
+ void checkMapKeySecure(Class<?> type) {
+ if (!isMapKeySecureType(type)) {
throw forbiddenClass(type.getName());
}
}
@@ -514,6 +816,37 @@ public final class JsonSharedRegistry {
return checkType(className, checker);
}
+ private boolean isCustomSecureType(Class<?> type) {
+ if (type.isArray()) {
+ return isCustomSecureType(TypeUtils.getArrayComponent(type));
+ }
+ if (!type.isEnum() && Enum.class.isAssignableFrom(type) && type != Enum.class) {
+ Class<?> enclosingClass = type.getEnclosingClass();
+ if (enclosingClass != null && enclosingClass.isEnum()) {
+ return isCustomSecureType(enclosingClass);
+ }
+ }
+ String className = type.getName();
+ DisallowedList.checkNotInDisallowedList(className);
+ JsonTypeChecker checker = typeChecker;
+ return checker == null || checkType(className, checker);
+ }
+
+ private boolean isMapKeySecureType(Class<?> type) {
+ if (type.isArray()) {
+ return isMapKeySecureType(TypeUtils.getArrayComponent(type));
+ }
+ String className = type.getName();
+ DisallowedList.checkNotInDisallowedList(className);
+ // A JsonValueCodec registration has no authority over a map-key occurrence. Preserve the
+ // ordinary exact built-in exemption even when the same raw class has a registered value codec.
+ if (exactCodecs.containsKey(type)) {
+ return true;
+ }
+ JsonTypeChecker checker = typeChecker;
+ return checker == null || checkType(className, checker);
+ }
+
private boolean checkType(String className, JsonTypeChecker checker) {
ConcurrentHashMap<String, Boolean> cache = typeCheckCache;
Boolean cached = cache.get(className);
@@ -621,4 +954,15 @@ public final class JsonSharedRegistry {
exactCodecs.put(ByteBuffer.class, ScalarCodecs.ByteBufferCodec.INSTANCE);
GuavaCodecs.registerExactCodecs(exactCodecs);
}
+
+ private static final class DeclarationCandidate {
+ private final Class<?> declarationType;
+ private final Class<? extends JsonValueCodec<?>> codecClass;
+
+ private DeclarationCandidate(
+ Class<?> declarationType, Class<? extends JsonValueCodec<?>> codecClass) {
+ this.declarationType = declarationType;
+ this.codecClass = codecClass;
+ }
+ }
}
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeInfo.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeInfo.java
index 27055f503..95024dfcd 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeInfo.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeInfo.java
@@ -20,7 +20,8 @@
package org.apache.fory.json.resolver;
import java.lang.reflect.Type;
-import org.apache.fory.json.codec.JsonCodec;
+import org.apache.fory.annotation.Internal;
+import org.apache.fory.json.codec.JsonValueCodec;
import org.apache.fory.json.codec.Latin1ReaderCodec;
import org.apache.fory.json.codec.ObjectCodec;
import org.apache.fory.json.codec.StringWriterCodec;
@@ -53,11 +54,22 @@ public final class JsonTypeInfo {
private Utf16ReaderCodec<Object> utf16Reader;
private Utf8ReaderCodec<Object> utf8Reader;
private final boolean defaultObjectCodec;
+ private final boolean annotationCodec;
- JsonTypeInfo(Type type, Class<?> rawType, JsonFieldKind kind, JsonCodec<Object> codec) {
+ JsonTypeInfo(Type type, Class<?> rawType, JsonFieldKind kind, JsonValueCodec<Object> codec) {
+ this(type, rawType, kind, codec, false);
+ }
+
+ JsonTypeInfo(
+ Type type,
+ Class<?> rawType,
+ JsonFieldKind kind,
+ JsonValueCodec<Object> codec,
+ boolean annotationCodec) {
this.type = type;
this.rawType = rawType;
this.kind = kind;
+ this.annotationCodec = annotationCodec;
stringWriter = codec;
utf8Writer = codec;
latin1Reader = codec;
@@ -123,4 +135,9 @@ public final class JsonTypeInfo {
public boolean usesDefaultObjectCodec() {
return defaultObjectCodec;
}
+
+ @Internal
+ public boolean usesAnnotationCodec() {
+ return annotationCodec;
+ }
}
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 13730e264..040916cf2 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
@@ -30,8 +30,8 @@ import org.apache.fory.annotation.Internal;
import org.apache.fory.collection.IdentityMap;
import org.apache.fory.json.codec.ClosedSubtypeCodec;
import org.apache.fory.json.codec.CodecUtils;
-import org.apache.fory.json.codec.JsonCodec;
import org.apache.fory.json.codec.JsonSubTypesInfo;
+import org.apache.fory.json.codec.JsonValueCodec;
import org.apache.fory.json.codec.Latin1ReaderCodec;
import org.apache.fory.json.codec.ObjectCodec;
import org.apache.fory.json.codec.ObjectCodec.AnyInfo;
@@ -44,7 +44,9 @@ import org.apache.fory.json.codegen.JsonJITContext;
import org.apache.fory.json.meta.JsonCreatorFieldInfo;
import org.apache.fory.json.meta.JsonCreatorInfo;
import org.apache.fory.json.meta.JsonFieldInfo;
+import org.apache.fory.json.meta.JsonFieldKind;
import org.apache.fory.json.meta.JsonFieldTable;
+import org.apache.fory.json.meta.JsonTypeUse;
import org.apache.fory.reflect.ReflectionUtils;
import org.apache.fory.reflect.TypeRef;
@@ -61,9 +63,10 @@ import org.apache.fory.reflect.TypeRef;
*
* <p>{@code typeInfos} owns declared and parameterized bindings. {@code objectCodecs} breaks
* recursive object-metadata construction by publishing the complete object owner before resolving
- * its fields. {@code objectTypeInfos} contains only canonical raw-class default-object bindings and
- * is the direct publication index for generated capabilities; custom, parameterized, container,
- * scalar, and dynamic bindings never enter it.
+ * its fields. {@code rawObjectTypeInfos} contains only canonical raw-class default-object bindings
+ * and is the publication index for generated capabilities. {@code canonicalObjectTypeInfos} indexes
+ * the same bindings by exact codec identity so custom and parameterized codecs never enter
+ * raw-class JIT dispatch.
*/
public final class JsonTypeResolver {
private final Map<Object, ObjectCodec<?>> objectCodecs;
@@ -71,7 +74,9 @@ public final class JsonTypeResolver {
private final JsonSharedRegistry sharedRegistry;
private final JsonCodegen codegen;
private final JsonJITContext jitContext;
- private final IdentityMap<Class<?>, JsonTypeInfo> objectTypeInfos;
+ private final IdentityMap<Class<?>, JsonTypeInfo> rawObjectTypeInfos;
+ private final IdentityMap<ObjectCodec<?>, JsonTypeInfo> canonicalObjectTypeInfos;
+ private int resolutionDepth;
private enum RuntimeObjectKey {
INSTANCE
@@ -83,7 +88,8 @@ public final class JsonTypeResolver {
typeInfos = new HashMap<>();
codegen = sharedRegistry.codegen();
jitContext = sharedRegistry.newJITContext();
- objectTypeInfos = new IdentityMap<>();
+ rawObjectTypeInfos = new IdentityMap<>();
+ canonicalObjectTypeInfos = new IdentityMap<>();
}
@Internal
@@ -104,11 +110,25 @@ public final class JsonTypeResolver {
private <T> ObjectCodec<T> getObjectCodec(TypeRef<T> ownerType) {
Class<?> rawType = ownerType.getRawType();
Object key = typeInfoKey(ownerType.getType(), rawType);
+ return getObjectCodec(ownerType, null, key);
+ }
+
+ @SuppressWarnings("unchecked")
+ private <T> ObjectCodec<T> getObjectCodec(
+ TypeRef<T> ownerType, JsonTypeUse ownerTypeUse, Object key) {
ObjectCodec<?> codec = objectCodecs.get(key);
if (codec != null) {
return (ObjectCodec<T>) codec;
}
- return buildObjectCodec(ownerType, key);
+ ResolutionSnapshot snapshot = beginResolution();
+ try {
+ return buildObjectCodec(ownerType, ownerTypeUse, key);
+ } catch (RuntimeException | Error e) {
+ rollbackResolution(snapshot);
+ throw e;
+ } finally {
+ endResolution();
+ }
}
public JsonTypeInfo getTypeInfo(Type declaredType, Class<?> fallback) {
@@ -118,69 +138,198 @@ public final class JsonTypeResolver {
if (typeInfo != null) {
return typeInfo;
}
- if (!sharedRegistry.hasCustomCodec(rawType)) {
- JsonSubTypesInfo definition = sharedRegistry.subTypesInfo(rawType);
- if (definition != null) {
- sharedRegistry.checkSecure(rawType);
- ClosedSubtypeCodec codec = new ClosedSubtypeCodec(rawType, definition);
- typeInfo = newTypeInfo(declaredType, rawType, codec);
- Set<Object> priorTypeKeys = new HashSet<>(typeInfos.keySet());
- Set<Object> priorObjectKeys = new HashSet<>(objectCodecs.keySet());
- // Closed graphs may recursively refer to their declared base through a subtype field or
- // container. Publish the complete dispatcher shell before resolving every finite branch;
- // failed tables are removed and can never leak a partially resolved binding.
- typeInfos.put(key, typeInfo);
- try {
- codec.resolve(this);
- return typeInfo;
- } catch (RuntimeException | Error e) {
- rollbackClosedMetadata(priorTypeKeys, priorObjectKeys);
- throw e;
+ ResolutionSnapshot snapshot = beginResolution();
+ try {
+ return resolveTypeInfo(declaredType, rawType, key);
+ } catch (RuntimeException | Error e) {
+ rollbackResolution(snapshot);
+ throw e;
+ } finally {
+ endResolution();
+ }
+ }
+
+ @Internal
+ public JsonTypeInfo getTypeInfo(JsonTypeUse typeUse) {
+ if (typeUse == null) {
+ throw new NullPointerException("typeUse");
+ }
+ if (!typeUse.hasExplicitCodec()) {
+ return getTypeInfo(typeUse.type(), typeUse.rawType());
+ }
+ JsonTypeInfo typeInfo = typeInfos.get(typeUse);
+ if (typeInfo != null) {
+ return typeInfo;
+ }
+ ResolutionSnapshot snapshot = beginResolution();
+ try {
+ return resolveTypeInfo(typeUse);
+ } catch (RuntimeException | Error e) {
+ rollbackResolution(snapshot);
+ throw e;
+ } finally {
+ endResolution();
+ }
+ }
+
+ private JsonTypeInfo resolveTypeInfo(JsonTypeUse typeUse) {
+ Type declaredType = typeUse.type();
+ Class<?> rawType = typeUse.rawType();
+ JsonTypeInfo typeInfo = customTypeInfo(typeUse);
+ if (typeInfo != null) {
+ typeInfos.put(typeUse, typeInfo);
+ return typeInfo;
+ }
+ JsonSubTypesInfo definition = sharedRegistry.subTypesInfo(rawType);
+ if (definition != null) {
+ typeUse.rejectExplicitDescendants(rawType.getTypeName());
+ sharedRegistry.checkSecure(rawType);
+ ClosedSubtypeCodec codec = new ClosedSubtypeCodec(rawType, definition);
+ typeInfo = newTypeInfo(declaredType, rawType, codec);
+ typeInfos.put(typeUse, typeInfo);
+ codec.resolve(this);
+ return typeInfo;
+ }
+ return buildTypeInfo(typeUse, typeUse);
+ }
+
+ private JsonTypeInfo resolveTypeInfo(Type declaredType, Class<?> rawType, Object key) {
+ JsonTypeInfo typeInfo = customTypeInfo(declaredType, rawType);
+ if (typeInfo != null) {
+ typeInfos.put(key, typeInfo);
+ return typeInfo;
+ }
+ JsonSubTypesInfo definition = sharedRegistry.subTypesInfo(rawType);
+ if (definition != null) {
+ sharedRegistry.checkSecure(rawType);
+ ClosedSubtypeCodec codec = new ClosedSubtypeCodec(rawType, definition);
+ typeInfo = newTypeInfo(declaredType, rawType, codec);
+ // Closed graphs may recursively refer to their declared base through a subtype field or
+ // container. Publish the complete dispatcher shell before resolving every finite branch.
+ // The outer cold-resolution transaction removes the complete provisional graph on failure.
+ typeInfos.put(key, typeInfo);
+ codec.resolve(this);
+ return typeInfo;
+ }
+ return buildTypeInfo(rawType, declaredType, key);
+ }
+
+ private JsonTypeInfo customTypeInfo(Type declaredType, Class<?> rawType) {
+ JsonValueCodec<?> codec = sharedRegistry.customCodec(rawType);
+ if (codec != null) {
+ sharedRegistry.checkCustomSecure(rawType);
+ return newTypeInfo(declaredType, rawType, JsonFieldKind.OBJECT, codec, false);
+ }
+ JsonCodecDeclaration declaration = sharedRegistry.codecDeclaration(rawType);
+ if (declaration == null) {
+ return null;
+ }
+ codec = sharedRegistry.annotationCodec(rawType, declaration.codecClass());
+ codec = declaration.bind(declaredType, rawType, codec);
+ return newTypeInfo(declaredType, rawType, JsonFieldKind.OBJECT, codec, true);
+ }
+
+ private JsonTypeInfo customTypeInfo(JsonTypeUse typeUse) {
+ Class<?> rawType = typeUse.rawType();
+ JsonValueCodec<?> codec;
+ boolean annotationCodec;
+ if (typeUse.hasCodec()) {
+ typeUse.rejectExplicitDescendants(rawType.getTypeName());
+ codec = sharedRegistry.annotationCodec(rawType, typeUse.codecClass());
+ annotationCodec = true;
+ } else {
+ codec = sharedRegistry.customCodec(rawType);
+ if (codec != null) {
+ typeUse.rejectExplicitDescendants(rawType.getTypeName());
+ sharedRegistry.checkCustomSecure(rawType);
+ annotationCodec = false;
+ } else {
+ JsonCodecDeclaration declaration = sharedRegistry.codecDeclaration(rawType);
+ if (declaration == null) {
+ return null;
}
+ typeUse.rejectExplicitDescendants(rawType.getTypeName());
+ codec = sharedRegistry.annotationCodec(rawType, declaration.codecClass());
+ codec = declaration.bind(typeUse.type(), rawType, codec);
+ annotationCodec = true;
}
}
- typeInfo = buildTypeInfo(rawType, declaredType);
- JsonTypeInfo recursiveTypeInfo = typeInfos.get(key);
- if (recursiveTypeInfo != null) {
- // Object metadata is published before its fields resolve. A recursive field can therefore
- // create this binding while the outer build is still running; retain that canonical owner so
- // every recursive field observes later capability installation.
- return recursiveTypeInfo;
- }
- typeInfos.put(key, typeInfo);
- registerObjectTypeInfo(typeInfo);
- return typeInfo;
+ return newTypeInfo(typeUse.type(), rawType, JsonFieldKind.OBJECT, codec, annotationCodec);
+ }
+
+ private ResolutionSnapshot beginResolution() {
+ ResolutionSnapshot snapshot =
+ resolutionDepth == 0
+ ? new ResolutionSnapshot(
+ new HashSet<>(typeInfos.keySet()), new HashSet<>(objectCodecs.keySet()))
+ : null;
+ resolutionDepth++;
+ return snapshot;
}
- private void rollbackClosedMetadata(Set<Object> priorTypeKeys, Set<Object> priorObjectKeys) {
- // Branch metadata created during the failed transaction may point to the provisional closed
- // dispatcher through recursive fields. Remove only those new owners; metadata and active JIT
- // work that predated this closed-table resolution remain canonical and untouched.
+ private void endResolution() {
+ resolutionDepth--;
+ }
+
+ private void rollbackResolution(ResolutionSnapshot snapshot) {
+ if (snapshot == null) {
+ return;
+ }
+ // Metadata created anywhere in a failed recursive graph may retain a provisional parent.
+ // Remove every new owner while preserving metadata and active JIT work that predated the
+ // outermost cold lookup.
Iterator<Map.Entry<Object, JsonTypeInfo>> typeIterator = typeInfos.entrySet().iterator();
while (typeIterator.hasNext()) {
Map.Entry<Object, JsonTypeInfo> entry = typeIterator.next();
- if (!priorTypeKeys.contains(entry.getKey())) {
+ if (!snapshot.typeKeys.contains(entry.getKey())) {
JsonTypeInfo value = entry.getValue();
- if (objectTypeInfos.get(value.rawType()) == value) {
- objectTypeInfos.remove(value.rawType());
+ if (rawObjectTypeInfos.get(value.rawType()) == value) {
+ rawObjectTypeInfos.remove(value.rawType());
+ ObjectCodec<?> owner = objectCodecs.get(value.rawType());
+ if (owner != null) {
+ canonicalObjectTypeInfos.remove(owner);
+ }
}
typeIterator.remove();
}
}
Iterator<Object> objectIterator = objectCodecs.keySet().iterator();
while (objectIterator.hasNext()) {
- if (!priorObjectKeys.contains(objectIterator.next())) {
+ if (!snapshot.objectKeys.contains(objectIterator.next())) {
objectIterator.remove();
}
}
}
+ private static final class ResolutionSnapshot {
+ private final Set<Object> typeKeys;
+ private final Set<Object> objectKeys;
+
+ private ResolutionSnapshot(Set<Object> typeKeys, Set<Object> objectKeys) {
+ this.typeKeys = typeKeys;
+ this.objectKeys = objectKeys;
+ }
+ }
+
public JsonTypeInfo getRuntimeTypeInfo(Class<?> runtimeType) {
Object key = runtimeType == Object.class ? RuntimeObjectKey.INSTANCE : runtimeType;
JsonTypeInfo typeInfo = typeInfos.get(key);
if (typeInfo != null) {
return typeInfo;
}
+ ResolutionSnapshot snapshot = beginResolution();
+ try {
+ return resolveRuntimeTypeInfo(runtimeType, key);
+ } catch (RuntimeException | Error e) {
+ rollbackResolution(snapshot);
+ throw e;
+ } finally {
+ endResolution();
+ }
+ }
+
+ private JsonTypeInfo resolveRuntimeTypeInfo(Class<?> runtimeType, Object key) {
+ JsonTypeInfo typeInfo;
typeInfo = buildRuntimeTypeInfo(runtimeType);
JsonTypeInfo recursiveTypeInfo = typeInfos.get(key);
if (recursiveTypeInfo != null) {
@@ -195,11 +344,16 @@ public final class JsonTypeResolver {
sharedRegistry.checkSecure(type);
}
+ @Internal
+ public void checkMapKeySecure(Class<?> type) {
+ sharedRegistry.checkMapKeySecure(type);
+ }
+
@SuppressWarnings("unchecked")
public <T> StringWriterCodec<T> stringWriter(ObjectCodec<T> codec) {
requireJITLock();
ObjectCodec<Object> owner = erase(codec);
- JsonTypeInfo typeInfo = objectTypeInfos.get(owner.type());
+ JsonTypeInfo typeInfo = canonicalObjectTypeInfos.get(owner);
if (typeInfo == null) {
return codec;
}
@@ -231,7 +385,7 @@ public final class JsonTypeResolver {
public <T> Utf8WriterCodec<T> utf8Writer(ObjectCodec<T> codec) {
requireJITLock();
ObjectCodec<Object> owner = erase(codec);
- JsonTypeInfo typeInfo = objectTypeInfos.get(owner.type());
+ JsonTypeInfo typeInfo = canonicalObjectTypeInfos.get(owner);
if (typeInfo == null) {
return codec;
}
@@ -263,7 +417,7 @@ public final class JsonTypeResolver {
public <T> Latin1ReaderCodec<T> latin1Reader(ObjectCodec<T> codec) {
requireJITLock();
ObjectCodec<Object> owner = erase(codec);
- JsonTypeInfo typeInfo = objectTypeInfos.get(owner.type());
+ JsonTypeInfo typeInfo = canonicalObjectTypeInfos.get(owner);
if (typeInfo == null) {
return codec;
}
@@ -295,7 +449,7 @@ public final class JsonTypeResolver {
public <T> Utf16ReaderCodec<T> utf16Reader(ObjectCodec<T> codec) {
requireJITLock();
ObjectCodec<Object> owner = erase(codec);
- JsonTypeInfo typeInfo = objectTypeInfos.get(owner.type());
+ JsonTypeInfo typeInfo = canonicalObjectTypeInfos.get(owner);
if (typeInfo == null) {
return codec;
}
@@ -327,7 +481,7 @@ public final class JsonTypeResolver {
public <T> Utf8ReaderCodec<T> utf8Reader(ObjectCodec<T> codec) {
requireJITLock();
ObjectCodec<Object> owner = erase(codec);
- JsonTypeInfo typeInfo = objectTypeInfos.get(owner.type());
+ JsonTypeInfo typeInfo = canonicalObjectTypeInfos.get(owner);
if (typeInfo == null) {
return codec;
}
@@ -360,7 +514,7 @@ public final class JsonTypeResolver {
ClosedSubtypeCodec parent, int index, ObjectCodec<?> codec, JsonFieldTable readTable) {
requireJITLock();
ObjectCodec<Object> owner = erase(codec);
- JsonTypeInfo typeInfo = objectTypeInfos.get(owner.type());
+ JsonTypeInfo typeInfo = canonicalObjectTypeInfos.get(owner);
if (typeInfo == null || codegen == null || !codegen.canCompileReader(owner)) {
return;
}
@@ -798,7 +952,10 @@ public final class JsonTypeResolver {
JsonFieldInfo[] fields = owner.writeFields();
for (int i = 0; i < fields.length; i++) {
Class<?> nestedType = JsonCodegen.writeNestedType(fields[i]);
- if (nestedType != null && nestedType != owner.type()) {
+ JsonTypeInfo child = fields[i].writeTypeInfo();
+ if (nestedType != null
+ && nestedType != owner.type()
+ && rawObjectTypeInfos.get(child.rawType()) == child) {
if (childFields == null) {
childFields = new Field[fields.length];
}
@@ -815,7 +972,9 @@ public final class JsonTypeResolver {
JsonCreatorFieldInfo[] fields = creator.fields();
for (int i = 0; i < fields.length; i++) {
JsonTypeInfo child = fields[i].typeInfo();
- if (child.usesDefaultObjectCodec() && child.rawType() != owner.type()) {
+ if (child.usesDefaultObjectCodec()
+ && child.rawType() != owner.type()
+ && rawObjectTypeInfos.get(child.rawType()) == child) {
if (childFields == null) {
childFields = new Field[fields.length];
}
@@ -827,7 +986,10 @@ public final class JsonTypeResolver {
JsonFieldInfo[] fields = owner.readFields();
for (int i = 0; i < fields.length; i++) {
Class<?> nestedType = JsonCodegen.readNestedType(fields[i]);
- if (nestedType != null && nestedType != owner.type()) {
+ JsonTypeInfo child = fields[i].readTypeInfo();
+ if (nestedType != null
+ && nestedType != owner.type()
+ && rawObjectTypeInfos.get(child.rawType()) == child) {
if (childFields == null) {
childFields = new Field[fields.length];
}
@@ -1165,18 +1327,20 @@ public final class JsonTypeResolver {
});
}
- private static boolean hasGeneratedAnyWriteChild(ObjectCodec<?> owner, AnyInfo any) {
+ private boolean hasGeneratedAnyWriteChild(ObjectCodec<?> owner, AnyInfo any) {
return any != null
&& (any.writeField() != null || any.writeGetter() != null)
&& any.valueTypeInfo().usesDefaultObjectCodec()
- && any.valueRawType() != owner.type();
+ && any.valueRawType() != owner.type()
+ && rawObjectTypeInfos.get(any.valueRawType()) == any.valueTypeInfo();
}
- private static boolean hasGeneratedAnyReadChild(ObjectCodec<?> owner, AnyInfo any) {
+ private boolean hasGeneratedAnyReadChild(ObjectCodec<?> owner, AnyInfo any) {
return any != null
&& (any.readField() != null || any.readSetter() != null)
&& any.valueTypeInfo().usesDefaultObjectCodec()
- && any.valueRawType() != owner.type();
+ && any.valueRawType() != owner.type()
+ && rawObjectTypeInfos.get(any.valueRawType()) == any.valueTypeInfo();
}
private static JsonTypeInfo readerChildTypeInfo(ObjectCodec<?> owner, int index) {
@@ -1187,45 +1351,102 @@ public final class JsonTypeResolver {
}
@SuppressWarnings("unchecked")
- private <T> ObjectCodec<T> buildObjectCodec(TypeRef<T> ownerType, Object key) {
+ private <T> ObjectCodec<T> buildObjectCodec(
+ TypeRef<T> ownerType, JsonTypeUse ownerTypeUse, Object key) {
ObjectCodec<?> cached = objectCodecs.get(key);
if (cached != null) {
return (ObjectCodec<T>) cached;
}
- Class<?> type = ownerType.getRawType();
- sharedRegistry.checkSecure(type);
- ObjectCodec<T> codec =
- ObjectCodec.build(
- ownerType,
- sharedRegistry.propertyDiscoveryEnabled(),
- sharedRegistry.propertyNamingStrategy(),
- sharedRegistry.writeNullFields());
+ ObjectCodec<T> codec = newObjectCodec(ownerType, ownerTypeUse);
// Publish the complete declared-type owner before resolving fields so recursive parameterized
// bindings resolve back to the same field table rather than the raw-class binding.
objectCodecs.put(key, codec);
- try {
- codec.resolveTypes(this);
- return codec;
- } catch (RuntimeException | Error e) {
- objectCodecs.remove(key, codec);
- throw e;
- }
+ // The outer resolution transaction owns failure cleanup. Keep this owner published until that
+ // rollback removes its canonical identity index and every other provisional graph entry.
+ codec.resolveTypes(this);
+ return codec;
+ }
+
+ private <T> ObjectCodec<T> newObjectCodec(TypeRef<T> ownerType, JsonTypeUse ownerTypeUse) {
+ sharedRegistry.checkSecure(ownerType.getRawType());
+ return ObjectCodec.build(
+ ownerType,
+ ownerTypeUse,
+ sharedRegistry.propertyDiscoveryEnabled(),
+ sharedRegistry.propertyNamingStrategy(),
+ sharedRegistry.writeNullFields());
}
- private JsonTypeInfo buildTypeInfo(Class<?> rawType, Type declaredType) {
+ private JsonTypeInfo buildTypeInfo(Class<?> rawType, Type declaredType, Object key) {
sharedRegistry.checkSecure(rawType);
TypeRef<?> typeRef = typeRef(declaredType, rawType);
- JsonCodec<?> codec = sharedRegistry.createCodec(rawType, typeRef, this);
+ JsonValueCodec<?> codec = sharedRegistry.createCodec(rawType, typeRef, this);
if (codec == null) {
- codec = getObjectCodec(typeRef);
+ return buildObjectTypeInfo(typeRef, null, key);
+ }
+ JsonTypeInfo recursiveTypeInfo = typeInfos.get(key);
+ if (recursiveTypeInfo != null) {
+ return recursiveTypeInfo;
+ }
+ JsonTypeInfo typeInfo = newTypeInfo(declaredType, rawType, codec);
+ typeInfos.put(key, typeInfo);
+ registerObjectTypeInfo(typeInfo);
+ return typeInfo;
+ }
+
+ private JsonTypeInfo buildTypeInfo(JsonTypeUse typeUse, Object key) {
+ Class<?> rawType = typeUse.rawType();
+ sharedRegistry.checkSecure(rawType);
+ JsonValueCodec<?> codec = sharedRegistry.createCodec(typeUse, this);
+ if (codec == null) {
+ TypeRef<?> typeRef = TypeRef.of(typeUse.type());
+ return buildObjectTypeInfo(typeRef, typeUse, key);
+ }
+ JsonTypeInfo recursiveTypeInfo = typeInfos.get(key);
+ if (recursiveTypeInfo != null) {
+ return recursiveTypeInfo;
+ }
+ JsonTypeInfo typeInfo = newTypeInfo(typeUse.type(), rawType, codec);
+ typeInfos.put(key, typeInfo);
+ registerObjectTypeInfo(typeInfo);
+ return typeInfo;
+ }
+
+ private JsonTypeInfo buildObjectTypeInfo(
+ TypeRef<?> ownerType, JsonTypeUse ownerTypeUse, Object key) {
+ JsonTypeInfo typeInfo = typeInfos.get(key);
+ if (typeInfo != null) {
+ return typeInfo;
}
- return newTypeInfo(declaredType, rawType, codec);
+ ObjectCodec<?> codec = objectCodecs.get(key);
+ if (codec == null) {
+ codec = newObjectCodec(ownerType, ownerTypeUse);
+ typeInfo = newTypeInfo(ownerType.getType(), ownerType.getRawType(), codec);
+ // The object codec and its heterogeneous type owner are one recursive metadata unit. Both
+ // must be visible before any field resolves so self-references reuse the same field table and
+ // capability slots. The outer cold-resolution transaction removes both on failure.
+ objectCodecs.put(key, codec);
+ typeInfos.put(key, typeInfo);
+ registerObjectTypeInfo(typeInfo);
+ codec.resolveTypes(this);
+ return typeInfo;
+ }
+ // A public getObjectCodec call may already own construction of this shell. Bind its type info
+ // now; the outer owner finishes field resolution before returning the codec to its caller.
+ typeInfo = newTypeInfo(ownerType.getType(), ownerType.getRawType(), codec);
+ typeInfos.put(key, typeInfo);
+ registerObjectTypeInfo(typeInfo);
+ return typeInfo;
}
private JsonTypeInfo buildRuntimeTypeInfo(Class<?> rawType) {
+ JsonTypeInfo custom = customTypeInfo(rawType, rawType);
+ if (custom != null) {
+ return custom;
+ }
sharedRegistry.checkSecure(rawType);
TypeRef<?> typeRef = TypeRef.of(rawType);
- JsonCodec<?> codec =
+ JsonValueCodec<?> codec =
rawType == Object.class
? getObjectCodec(typeRef)
: sharedRegistry.createCodec(rawType, typeRef, this);
@@ -1235,15 +1456,26 @@ public final class JsonTypeResolver {
return newTypeInfo(rawType, rawType, codec);
}
- private JsonTypeInfo newTypeInfo(Type type, Class<?> rawType, JsonCodec<?> codec) {
+ private JsonTypeInfo newTypeInfo(Type type, Class<?> rawType, JsonValueCodec<?> codec) {
return new JsonTypeInfo(type, rawType, sharedRegistry.kind(rawType), bindCodec(codec));
}
+ private JsonTypeInfo newTypeInfo(
+ Type type,
+ Class<?> rawType,
+ JsonFieldKind kind,
+ JsonValueCodec<?> codec,
+ boolean annotationCodec) {
+ return new JsonTypeInfo(type, rawType, kind, bindCodec(codec), annotationCodec);
+ }
+
private void registerObjectTypeInfo(JsonTypeInfo typeInfo) {
if (typeInfo.usesDefaultObjectCodec()
&& typeInfo.type() instanceof Class
&& typeInfo.rawType() != Object.class) {
- objectTypeInfos.put(typeInfo.rawType(), typeInfo);
+ ObjectCodec<?> owner = (ObjectCodec<?>) typeInfo.stringWriter();
+ rawObjectTypeInfos.put(typeInfo.rawType(), typeInfo);
+ canonicalObjectTypeInfos.put(owner, typeInfo);
}
}
@@ -1277,10 +1509,10 @@ public final class JsonTypeResolver {
}
@SuppressWarnings("unchecked")
- private static JsonCodec<Object> bindCodec(JsonCodec<?> codec) {
+ private static JsonValueCodec<Object> bindCodec(JsonValueCodec<?> codec) {
// The resolver has already matched the codec to this binding's declared type. JsonTypeInfo is
// deliberately heterogeneous, so erase that proven relation once instead of casting in every
// root, field, container, and generated hot call.
- return (JsonCodec<Object>) codec;
+ return (JsonValueCodec<Object>) codec;
}
}
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 9758328bc..592b9b305 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
@@ -49,11 +49,13 @@ import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
+import org.apache.fory.collection.IdentityMap;
import org.apache.fory.json.annotation.JsonAnyProperty;
+import org.apache.fory.json.annotation.JsonCodec;
import org.apache.fory.json.annotation.JsonCreator;
import org.apache.fory.json.annotation.JsonSubTypes;
import org.apache.fory.json.codec.ClosedSubtypeCodec;
-import org.apache.fory.json.codec.JsonCodec;
+import org.apache.fory.json.codec.JsonValueCodec;
import org.apache.fory.json.codec.Latin1ReaderCodec;
import org.apache.fory.json.codec.ObjectCodec;
import org.apache.fory.json.codec.StringWriterCodec;
@@ -63,6 +65,7 @@ import org.apache.fory.json.codec.Utf8WriterCodec;
import org.apache.fory.json.codegen.JsonJITContext;
import org.apache.fory.json.data.RecursiveParent;
import org.apache.fory.json.meta.JsonFieldInfo;
+import org.apache.fory.json.meta.JsonTypeUse;
import org.apache.fory.json.reader.Latin1JsonReader;
import org.apache.fory.json.reader.Utf16JsonReader;
import org.apache.fory.json.reader.Utf8JsonReader;
@@ -72,8 +75,10 @@ import org.apache.fory.json.resolver.JsonTypeInfo;
import org.apache.fory.json.resolver.JsonTypeResolver;
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.apache.fory.serializer.StringSerializer;
+import org.testng.SkipException;
import org.testng.annotations.Test;
public class JsonAsyncCompilationTest {
@@ -348,6 +353,25 @@ public class JsonAsyncCompilationTest {
assertSame(replacement.utf8Reader(), replacementOwner);
}
+ @Test
+ public void rollbackClearsCanonicalOwners() throws Exception {
+ FlakyStringCodec.CONSTRUCTIONS.set(0);
+ ControlledJson controlled = controlledJson();
+ JsonTypeResolver resolver = new JsonTypeResolver(controlled.registry);
+ Field field = JsonTypeResolver.class.getDeclaredField("canonicalObjectTypeInfos");
+ field.setAccessible(true);
+ IdentityMap<?, ?> canonicalOwners = (IdentityMap<?, ?>) field.get(resolver);
+
+ expectThrows(ForyJsonException.class, () -> resolver.getObjectCodec(RollbackAfterSelf.class));
+ assertEquals(canonicalOwners.size, 0);
+
+ ObjectCodec<RollbackAfterSelf> replacement = resolver.getObjectCodec(RollbackAfterSelf.class);
+ JsonTypeInfo replacementInfo =
+ resolver.getTypeInfo(RollbackAfterSelf.class, RollbackAfterSelf.class);
+ assertSame(replacementInfo.stringWriter(), replacement);
+ assertEquals(canonicalOwners.size, 1);
+ }
+
@Test
public void asyncFailureKeepsInterpretedResult() {
ControlledExecutor executor = new ControlledExecutor();
@@ -613,7 +637,7 @@ public class JsonAsyncCompilationTest {
controlled.executor.runNext();
assertSame(parameterized.utf8Reader(), parameterizedReader);
- JsonCodec<AsyncChild> codec = nullCodec();
+ JsonValueCodec<AsyncChild> codec = nullCodec();
CodecRegistry codecs = new CodecRegistry();
codecs.register(AsyncChild.class, codec);
ControlledJson custom = controlledJson(codecs);
@@ -628,6 +652,83 @@ public class JsonAsyncCompilationTest {
assertEquals(custom.executor.submittedTasks(), 0);
}
+ @Test
+ public void annotatedBindingsStayIsolated() throws Exception {
+ if (JdkVersion.MAJOR_VERSION <= 11) {
+ throw new SkipException(
+ "JDK 11 and earlier do not expose member-class generic field type-use metadata");
+ }
+ assertBindingOrder(false);
+ assertBindingOrder(true);
+ }
+
+ private static void assertBindingOrder(boolean annotatedFirst) throws Exception {
+ ControlledJson controlled = controlledJson();
+ JsonTypeResolver resolver = primaryTypeResolver(controlled.json);
+ JsonTypeUse annotatedUse = JsonTypeUse.forField(AsyncBindingOwner.class.getField("annotated"));
+ JsonTypeInfo annotatedInfo;
+ JsonTypeInfo rawInfo;
+ resolver.lockJIT();
+ try {
+ if (annotatedFirst) {
+ annotatedInfo = resolver.getTypeInfo(annotatedUse);
+ rawInfo = resolver.getTypeInfo(GenericAsyncBox.class, GenericAsyncBox.class);
+ } else {
+ rawInfo = resolver.getTypeInfo(GenericAsyncBox.class, GenericAsyncBox.class);
+ annotatedInfo = resolver.getTypeInfo(annotatedUse);
+ }
+ ObjectCodec<?> annotatedOwner = (ObjectCodec<?>) annotatedInfo.stringWriter();
+ ObjectCodec<?> rawOwner = (ObjectCodec<?>) rawInfo.stringWriter();
+ assertNotSame(annotatedOwner, rawOwner);
+ assertSame(resolver.stringWriter(annotatedOwner), annotatedOwner);
+ assertSame(resolver.utf8Writer(annotatedOwner), annotatedOwner);
+ assertSame(resolver.latin1Reader(annotatedOwner), annotatedOwner);
+ assertSame(resolver.utf16Reader(annotatedOwner), annotatedOwner);
+ assertSame(resolver.utf8Reader(annotatedOwner), annotatedOwner);
+ assertSame(resolver.stringWriter(rawOwner), rawOwner);
+ assertSame(resolver.utf8Writer(rawOwner), rawOwner);
+ assertSame(resolver.latin1Reader(rawOwner), rawOwner);
+ assertSame(resolver.utf16Reader(rawOwner), rawOwner);
+ assertSame(resolver.utf8Reader(rawOwner), rawOwner);
+ } finally {
+ resolver.unlockJIT();
+ }
+ controlled.executor.runAll();
+
+ AsyncBindingOwner value = new AsyncBindingOwner();
+ value.raw = new GenericAsyncBox<>();
+ value.raw.value = "raw";
+ value.annotated = new GenericAsyncBox<>();
+ value.annotated.value = "annotated";
+ String expected = "{\"annotated\":{\"value\":\"codec:annotated\"},\"raw\":{\"value\":\"raw\"}}";
+ assertEquals(controlled.json.toJson(value), expected);
+ controlled.executor.runAll();
+ assertEquals(controlled.json.toJson(value), expected);
+ assertEquals(new String(controlled.json.toJsonBytes(value), StandardCharsets.UTF_8), expected);
+ controlled.executor.runAll();
+ assertEquals(new String(controlled.json.toJsonBytes(value), StandardCharsets.UTF_8), expected);
+ assertEquals(
+ controlled.json.fromJson(expected, AsyncBindingOwner.class).annotated.value, "annotated");
+ controlled.executor.runAll();
+ assertEquals(
+ controlled.json.fromJson(expected, AsyncBindingOwner.class).annotated.value, "annotated");
+ String utf16 = "{\"annotated\":{\"value\":\"codec:你\"},\"raw\":{\"value\":\"raw\"}}";
+ assertEquals(controlled.json.fromJson(utf16, AsyncBindingOwner.class).annotated.value, "你");
+ controlled.executor.runAll();
+ assertEquals(controlled.json.fromJson(utf16, AsyncBindingOwner.class).annotated.value, "你");
+ assertEquals(
+ controlled.json.fromJson(expected.getBytes(StandardCharsets.UTF_8), AsyncBindingOwner.class)
+ .annotated
+ .value,
+ "annotated");
+ controlled.executor.runAll();
+ assertEquals(
+ controlled.json.fromJson(expected.getBytes(StandardCharsets.UTF_8), AsyncBindingOwner.class)
+ .annotated
+ .value,
+ "annotated");
+ }
+
@Test
public void nestedAndRecursiveTypes() throws Exception {
ControlledJson controlled = controlledJson();
@@ -980,7 +1081,7 @@ public class JsonAsyncCompilationTest {
}
}
- private static final class BlockingCodec implements JsonCodec<BlockingValue> {
+ private static final class BlockingCodec implements JsonValueCodec<BlockingValue> {
private final CountDownLatch entered;
private final CountDownLatch release;
@@ -1120,11 +1221,70 @@ public class JsonAsyncCompilationTest {
public T value;
}
+ public static final class AsyncBindingOwner {
+ public GenericAsyncBox<@JsonCodec(AsyncStringCodec.class) String> annotated;
+ public GenericAsyncBox raw;
+ }
+
+ public static final class AsyncStringCodec implements JsonValueCodec<String> {
+ @Override
+ public void writeString(StringJsonWriter writer, String value) {
+ writer.writeString("codec:" + value);
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, String value) {
+ writer.writeString("codec:" + value);
+ }
+
+ @Override
+ public String readLatin1(Latin1JsonReader reader) {
+ return read(reader.readString());
+ }
+
+ @Override
+ public String readUtf16(Utf16JsonReader reader) {
+ return read(reader.readString());
+ }
+
+ @Override
+ public String readUtf8(Utf8JsonReader reader) {
+ return read(reader.readString());
+ }
+
+ private static String read(String value) {
+ if (!value.startsWith("codec:")) {
+ throw new ForyJsonException("Missing codec prefix");
+ }
+ return value.substring("codec:".length());
+ }
+ }
+
public static final class SelfRecursive {
public int id;
public SelfRecursive next;
}
+ public static final class RollbackAfterSelf {
+ public RollbackAfterSelf aSelf;
+ public @JsonCodec(FlakyStringCodec.class) String zValue;
+ }
+
+ public static final class FlakyStringCodec extends JsonCodecAnnotationTest.TaggedStringCodec {
+ private static final AtomicInteger CONSTRUCTIONS = new AtomicInteger();
+
+ public FlakyStringCodec() {
+ if (CONSTRUCTIONS.getAndIncrement() == 0) {
+ throw new IllegalStateException("expected first construction failure");
+ }
+ }
+
+ @Override
+ protected String tag() {
+ return "rollback";
+ }
+ }
+
public static final class MutualFirst {
public MutualSecond second;
}
diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonCodecAnnotationTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonCodecAnnotationTest.java
new file mode 100644
index 000000000..a499c4430
--- /dev/null
+++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonCodecAnnotationTest.java
@@ -0,0 +1,970 @@
+/*
+ * 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.assertTrue;
+import static org.testng.Assert.fail;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.atomic.AtomicReferenceArray;
+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.JsonCodec;
+import org.apache.fory.json.annotation.JsonCreator;
+import org.apache.fory.json.annotation.JsonProperty;
+import org.apache.fory.json.codec.JsonValueCodec;
+import org.apache.fory.json.reader.JsonReader;
+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.JsonWriter;
+import org.apache.fory.json.writer.StringJsonWriter;
+import org.apache.fory.json.writer.Utf8JsonWriter;
+import org.apache.fory.platform.JdkVersion;
+import org.testng.SkipException;
+import org.testng.annotations.Factory;
+import org.testng.annotations.Test;
+
+public class JsonCodecAnnotationTest extends ForyJsonTestModels {
+ @Factory(dataProvider = "enableCodegen")
+ public JsonCodecAnnotationTest(boolean codegen) {
+ super(codegen);
+ }
+
+ @Test
+ public void representations() {
+ ForyJson json = newJson();
+ RepresentationModel value = new RepresentationModel();
+ value.value = "x";
+ String expected = "{\"value\":\"P:x\"}";
+ assertEquals(json.toJson(value), expected);
+ assertEquals(new String(json.toJsonBytes(value), StandardCharsets.UTF_8), expected);
+ assertEquals(
+ json.fromJson(expected, RepresentationModel.class).value,
+ JsonTestSupport.stringReaderPath(expected) + ":x");
+ assertEquals(
+ json.fromJson("{\"value\":\"P:你好\"}", RepresentationModel.class).value, "utf16:你好");
+ assertEquals(
+ json.fromJson(expected.getBytes(StandardCharsets.UTF_8), RepresentationModel.class).value,
+ "utf8:x");
+ }
+
+ @Test
+ public void propertyMerge() {
+ ForyJson json = newJson();
+ MergedProperty value = new MergedProperty();
+ value.setValue("x");
+ assertEquals(json.toJson(value), "{\"value\":\"A:x\"}");
+ assertEquals(json.fromJson("{\"value\":\"A:y\"}", MergedProperty.class).getValue(), "y");
+ }
+
+ @Test
+ public void propertyConflict() {
+ assertFailure(
+ () -> newJson().toJson(new ConflictingProperty()),
+ "Conflicting @JsonCodec values",
+ AStringCodec.class.getName(),
+ BStringCodec.class.getName());
+ }
+
+ @Test
+ public void creators() {
+ ForyJson json = newJson();
+ PropertyListCreator listed = json.fromJson("{\"value\":\"A:list\"}", PropertyListCreator.class);
+ assertEquals(listed.value, "list");
+ assertEquals(json.toJson(listed), "{\"value\":\"A:list\"}");
+
+ ParameterLocalCreator local =
+ json.fromJson("{\"value\":\"A:local\"}", ParameterLocalCreator.class);
+ assertEquals(local.getValue(), "local");
+ assertEquals(json.toJson(local), "{\"value\":\"A:local\"}");
+
+ CreatorOnly only = json.fromJson("{\"input\":\"A:only\"}", CreatorOnly.class);
+ assertEquals(only.decoded, "only");
+ assertEquals(json.toJson(only), "{}");
+ }
+
+ @Test
+ public void recordComponent() throws Exception {
+ if (JdkVersion.MAJOR_VERSION < 17) {
+ throw new SkipException("Java record test requires JDK 17+");
+ }
+ Class<?> type =
+ compileRecordClass(
+ "JsonCodecTypeUseRecord",
+ "package org.apache.fory.json.records;\n"
+ + "import org.apache.fory.json.annotation.JsonCodec;\n"
+ + "import org.apache.fory.json.JsonCodecAnnotationTest.AStringCodec;\n"
+ + "public record JsonCodecTypeUseRecord("
+ + "@JsonCodec(AStringCodec.class) String value) {}\n");
+ Object value = type.getConstructor(String.class).newInstance("x");
+ assertEquals(jsonText(newJson(), value), "{\"value\":\"A:x\"}");
+ Object decoded = newJson().fromJson("{\"value\":\"A:y\"}", type);
+ assertEquals(type.getMethod("value").invoke(decoded), "y");
+ }
+
+ @Test
+ public void anyValues() {
+ ForyJson json = newJson();
+ FieldAny field = new FieldAny();
+ field.values.put("x", "one");
+ assertEquals(json.toJson(field), "{\"x\":\"A:one\"}");
+ assertEquals(json.fromJson("{\"x\":\"A:two\"}", FieldAny.class).values.get("x"), "two");
+
+ MethodAny method = new MethodAny();
+ method.values.put("x", "three");
+ assertEquals(json.toJson(method), "{\"x\":\"A:three\"}");
+ assertEquals(json.fromJson("{\"x\":\"A:four\"}", MethodAny.class).values.get("x"), "four");
+ }
+
+ @Test
+ public void anyRejections() {
+ assertFailure(
+ () -> newJson().toJson(new OuterAny()), "cannot select the flattened JSON Any map");
+ assertFailure(() -> newJson().toJson(new KeyAny()), "map-key subtree");
+ }
+
+ @Test
+ public void scalarNodes() {
+ ForyJson json = newJson();
+ ScalarModel value = new ScalarModel();
+ value.number = 7;
+ value.text = "text";
+ value.kind = ScalarKind.ONE;
+ value.object = new Value("object");
+ String text = json.toJson(value);
+ assertEquals(new String(json.toJsonBytes(value), StandardCharsets.UTF_8), text);
+ assertTrue(text.contains("\"number\":1007"));
+ assertTrue(text.contains("\"text\":\"A:text\""));
+ assertTrue(text.contains("\"kind\":\"E:ONE\""));
+ assertTrue(text.contains("\"object\":\"V:object\""));
+
+ ScalarModel decoded =
+ json.fromJson(
+ "{\"number\":1008,\"text\":\"A:value\",\"kind\":\"E:TWO\","
+ + "\"object\":\"V:nested\"}",
+ ScalarModel.class);
+ assertEquals(decoded.number, 8);
+ assertEquals(decoded.text, "value");
+ assertEquals(decoded.kind, ScalarKind.TWO);
+ assertEquals(decoded.object.text, "nested");
+ }
+
+ @Test
+ public void arrayNodes() {
+ ForyJson json = newJson();
+ WholeArray whole = new WholeArray();
+ whole.value = new String[] {"ignored"};
+ assertEquals(json.toJson(whole), "{\"value\":\"whole-array\"}");
+ assertEquals(
+ json.fromJson("{\"value\":\"whole-array\"}", WholeArray.class).value,
+ new String[] {"whole-array"});
+
+ ComponentArray components = new ComponentArray();
+ components.value = new String[] {"x", "y"};
+ assertEquals(json.toJson(components), "{\"value\":[\"A:x\",\"A:y\"]}");
+ assertEquals(
+ json.fromJson("{\"value\":[\"A:a\",\"A:b\"]}", ComponentArray.class).value,
+ new String[] {"a", "b"});
+
+ MultiArray multi = new MultiArray();
+ multi.value = new String[][] {{"x"}};
+ assertEquals(json.toJson(multi), "{\"value\":[[\"A:x\"]]}");
+ assertEquals(json.fromJson("{\"value\":[[\"A:z\"]]}", MultiArray.class).value[0][0], "z");
+ }
+
+ @Test
+ public void collections() {
+ ForyJson json = newJson();
+ ListModel list = new ListModel();
+ list.value = Arrays.asList("x");
+ assertEquals(json.toJson(list), "{\"value\":[\"A:x\"]}");
+ assertEquals(json.fromJson("{\"value\":[\"A:y\"]}", ListModel.class).value, Arrays.asList("y"));
+
+ SetModel set = new SetModel();
+ set.value = new LinkedHashSet<>(Arrays.asList("x"));
+ assertEquals(json.toJson(set), "{\"value\":[\"A:x\"]}");
+ assertTrue(json.fromJson("{\"value\":[\"A:y\"]}", SetModel.class).value.contains("y"));
+
+ CollectionModel collection = new CollectionModel();
+ collection.value = Arrays.asList("x");
+ assertEquals(json.toJson(collection), "{\"value\":[\"A:x\"]}");
+ assertEquals(
+ new ArrayList<>(json.fromJson("{\"value\":[\"A:y\"]}", CollectionModel.class).value),
+ Arrays.asList("y"));
+
+ ConcreteListModel concrete = new ConcreteListModel();
+ concrete.value = new ArrayList<>(Arrays.asList("x"));
+ assertEquals(json.toJson(concrete), "{\"value\":[\"A:x\"]}");
+ assertEquals(
+ json.fromJson("{\"value\":[\"A:y\"]}", ConcreteListModel.class).value, Arrays.asList("y"));
+ }
+
+ @Test
+ public void reorderedCollection() {
+ if (JdkVersion.MAJOR_VERSION <= 11) {
+ throw new SkipException(
+ "JDK 11 and earlier do not expose member-class generic field type-use metadata");
+ }
+ ForyJson json = newJson();
+ ReorderedListModel reordered = new ReorderedListModel();
+ reordered.value = new ReorderedList<>();
+ reordered.value.add("x");
+ assertEquals(json.toJson(reordered), "{\"value\":[\"A:x\"]}");
+ assertEquals(
+ json.fromJson("{\"value\":[\"A:y\"]}", ReorderedListModel.class).value, Arrays.asList("y"));
+ }
+
+ @Test
+ public void mapValues() {
+ ForyJson json = newJson();
+ MapModel value = new MapModel();
+ value.values.put("x", "one");
+ assertEquals(json.toJson(value), "{\"values\":{\"x\":\"A:one\"}}");
+ assertEquals(
+ json.fromJson("{\"values\":{\"x\":\"A:two\"}}", MapModel.class).values.get("x"), "two");
+ assertFailure(() -> newJson().toJson(new MapKeyModel()), "map-key subtree");
+ }
+
+ @Test
+ public void references() {
+ ForyJson json = newJson();
+ OptionalModel optional = new OptionalModel();
+ optional.value = Optional.of("x");
+ assertEquals(json.toJson(optional), "{\"value\":\"A:x\"}");
+ assertEquals(json.fromJson("{\"value\":\"A:y\"}", OptionalModel.class).value, Optional.of("y"));
+
+ AtomicModel atomic = new AtomicModel();
+ atomic.value = new AtomicReference<>("x");
+ assertEquals(json.toJson(atomic), "{\"value\":\"A:x\"}");
+ assertEquals(json.fromJson("{\"value\":\"A:y\"}", AtomicModel.class).value.get(), "y");
+
+ AtomicArrayModel array = new AtomicArrayModel();
+ array.value = new AtomicReferenceArray<>(new String[] {"x"});
+ assertEquals(json.toJson(array), "{\"value\":[\"A:x\"]}");
+ assertEquals(json.fromJson("{\"value\":[\"A:y\"]}", AtomicArrayModel.class).value.get(0), "y");
+ }
+
+ @Test
+ public void ownerSubstitution() {
+ if (JdkVersion.MAJOR_VERSION <= 11) {
+ throw new SkipException(
+ "JDK 11 and earlier do not expose member-class generic field type-use metadata");
+ }
+ ForyJson json = newJson();
+ EnvelopeOwner owner = new EnvelopeOwner();
+ owner.envelope = new Envelope<>();
+ owner.envelope.value = "x";
+ assertEquals(json.toJson(owner), "{\"envelope\":{\"value\":\"A:x\"}}");
+ assertEquals(
+ json.fromJson("{\"envelope\":{\"value\":\"A:y\"}}", EnvelopeOwner.class).envelope.value,
+ "y");
+ }
+
+ @Test
+ public void equalOwnerCodec() {
+ ForyJson json = newJson();
+ EqualEnvelopeOwner equal = new EqualEnvelopeOwner();
+ equal.envelope = new AnnotatedEnvelope<>();
+ equal.envelope.value = "x";
+ assertEquals(json.toJson(equal), "{\"envelope\":{\"value\":\"A:x\"}}");
+ assertEquals(
+ json.fromJson("{\"envelope\":{\"value\":\"A:y\"}}", EqualEnvelopeOwner.class)
+ .envelope
+ .value,
+ "y");
+ }
+
+ @Test
+ public void ownerConflict() {
+ if (JdkVersion.MAJOR_VERSION <= 11) {
+ throw new SkipException(
+ "JDK 11 and earlier do not expose member-class generic field type-use metadata");
+ }
+ assertFailure(
+ () -> newJson().toJson(new ConflictingEnvelopeOwner()),
+ "Conflicting @JsonCodec values",
+ AStringCodec.class.getName(),
+ BStringCodec.class.getName());
+ }
+
+ @Test
+ public void rawOwnerFailure() {
+ assertFailure(
+ () -> newJson().toJson(new RawEnvelopeOwner()),
+ "does not resolve to one concrete target",
+ "AnnotatedEnvelope");
+ }
+
+ @Test
+ public void cacheIsolation() {
+ ForyJson json = newJson();
+ CacheModel value = new CacheModel();
+ value.plain = "plain";
+ value.a = "one";
+ value.sameA = "two";
+ value.b = "three";
+ String text = json.toJson(value);
+ assertTrue(text.contains("\"plain\":\"plain\""));
+ assertTrue(text.contains("\"a\":\"A:one\""));
+ assertTrue(text.contains("\"sameA\":\"A:two\""));
+ assertTrue(text.contains("\"b\":\"B:three\""));
+
+ CacheModel decoded =
+ json.fromJson(
+ "{\"plain\":\"plain\",\"a\":\"A:one\",\"sameA\":\"A:two\"," + "\"b\":\"B:three\"}",
+ CacheModel.class);
+ assertEquals(decoded.plain, "plain");
+ assertEquals(decoded.a, "one");
+ assertEquals(decoded.sameA, "two");
+ assertEquals(decoded.b, "three");
+ }
+
+ @Test
+ public void precedence() {
+ ForyJson defaults = newJson();
+ assertEquals(defaults.toJson(new PrecedenceValue()), "\"declared\"");
+ assertEquals(defaults.toJson(new InheritedPrecedenceValue()), "\"declared\"");
+
+ ForyJson registered =
+ newJsonBuilder().registerCodec(PrecedenceValue.class, new BuilderPrecedenceCodec()).build();
+ PrecedenceHolder holder = new PrecedenceHolder();
+ holder.local = new PrecedenceValue();
+ holder.regular = new PrecedenceValue();
+ String text = registered.toJson(holder);
+ assertTrue(text.contains("\"local\":\"local\""));
+ assertTrue(text.contains("\"regular\":\"builder\""));
+
+ ForyJson inheritedRegistered =
+ newJsonBuilder()
+ .registerCodec(InheritedPrecedenceValue.class, new BuilderChildCodec())
+ .build();
+ InheritedPrecedenceHolder inherited = new InheritedPrecedenceHolder();
+ inherited.local = new InheritedPrecedenceValue();
+ inherited.regular = new InheritedPrecedenceValue();
+ text = inheritedRegistered.toJson(inherited);
+ assertTrue(text.contains("\"local\":\"local\""));
+ assertTrue(text.contains("\"regular\":\"builder-child\""));
+ }
+
+ @Test
+ public void hiddenDescendants() {
+ assertFailure(() -> newJson().toJson(new HiddenExplicit()), "hides descendant @JsonCodec");
+
+ HiddenDefault value = new HiddenDefault();
+ value.values = Arrays.asList(new DeclaredValue());
+ assertEquals(newJson().toJson(value), "{\"values\":\"whole-default\"}");
+ }
+
+ private static String jsonText(ForyJson json, Object value) {
+ String text = json.toJson(value);
+ assertEquals(new String(json.toJsonBytes(value), StandardCharsets.UTF_8), text);
+ return text;
+ }
+
+ private static void assertFailure(FailureCall call, String... fragments) {
+ try {
+ call.run();
+ fail("Expected ForyJsonException");
+ } catch (ForyJsonException e) {
+ for (String fragment : fragments) {
+ assertTrue(e.getMessage().contains(fragment), e.getMessage());
+ }
+ }
+ }
+
+ private interface FailureCall {
+ void run();
+ }
+
+ public abstract static class TaggedStringCodec implements JsonValueCodec<String> {
+ protected abstract String tag();
+
+ @Override
+ public final void writeString(StringJsonWriter writer, String value) {
+ writeTagged(writer, value, tag());
+ }
+
+ @Override
+ public final void writeUtf8(Utf8JsonWriter writer, String value) {
+ writeTagged(writer, value, tag());
+ }
+
+ @Override
+ public final String readLatin1(Latin1JsonReader reader) {
+ return readTagged(reader, tag());
+ }
+
+ @Override
+ public final String readUtf16(Utf16JsonReader reader) {
+ return readTagged(reader, tag());
+ }
+
+ @Override
+ public final String readUtf8(Utf8JsonReader reader) {
+ return readTagged(reader, tag());
+ }
+ }
+
+ public static class AStringCodec extends TaggedStringCodec {
+ @Override
+ protected String tag() {
+ return "A";
+ }
+ }
+
+ public static class BStringCodec extends TaggedStringCodec {
+ @Override
+ protected String tag() {
+ return "B";
+ }
+ }
+
+ public static class PathStringCodec implements JsonValueCodec<String> {
+ @Override
+ public void writeString(StringJsonWriter writer, String value) {
+ writeTagged(writer, value, "P");
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, String value) {
+ writeTagged(writer, value, "P");
+ }
+
+ @Override
+ public String readLatin1(Latin1JsonReader reader) {
+ return "latin1:" + readTagged(reader, "P");
+ }
+
+ @Override
+ public String readUtf16(Utf16JsonReader reader) {
+ return "utf16:" + readTagged(reader, "P");
+ }
+
+ @Override
+ public String readUtf8(Utf8JsonReader reader) {
+ return "utf8:" + readTagged(reader, "P");
+ }
+ }
+
+ public static class IntCodec implements JsonValueCodec<Integer> {
+ @Override
+ public void writeString(StringJsonWriter writer, Integer value) {
+ writer.writeInt(value.intValue() + 1000);
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, Integer value) {
+ writer.writeInt(value.intValue() + 1000);
+ }
+
+ @Override
+ public Integer readLatin1(Latin1JsonReader reader) {
+ return Integer.valueOf(reader.readInt() - 1000);
+ }
+
+ @Override
+ public Integer readUtf16(Utf16JsonReader reader) {
+ return Integer.valueOf(reader.readInt() - 1000);
+ }
+
+ @Override
+ public Integer readUtf8(Utf8JsonReader reader) {
+ return Integer.valueOf(reader.readInt() - 1000);
+ }
+ }
+
+ public static class EnumCodec implements JsonValueCodec<ScalarKind> {
+ @Override
+ public void writeString(StringJsonWriter writer, ScalarKind value) {
+ writer.writeString("E:" + value.name());
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, ScalarKind value) {
+ writer.writeString("E:" + value.name());
+ }
+
+ @Override
+ public ScalarKind readLatin1(Latin1JsonReader reader) {
+ return readEnum(reader);
+ }
+
+ @Override
+ public ScalarKind readUtf16(Utf16JsonReader reader) {
+ return readEnum(reader);
+ }
+
+ @Override
+ public ScalarKind readUtf8(Utf8JsonReader reader) {
+ return readEnum(reader);
+ }
+ }
+
+ public static class ValueCodec implements JsonValueCodec<Value> {
+ @Override
+ public void writeString(StringJsonWriter writer, Value value) {
+ writer.writeString("V:" + value.text);
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, Value value) {
+ writer.writeString("V:" + value.text);
+ }
+
+ @Override
+ public Value readLatin1(Latin1JsonReader reader) {
+ return readValue(reader);
+ }
+
+ @Override
+ public Value readUtf16(Utf16JsonReader reader) {
+ return readValue(reader);
+ }
+
+ @Override
+ public Value readUtf8(Utf8JsonReader reader) {
+ return readValue(reader);
+ }
+ }
+
+ public abstract static class ConstantCodec<T> implements JsonValueCodec<T> {
+ protected abstract String text();
+
+ protected abstract T value();
+
+ @Override
+ public final void writeString(StringJsonWriter writer, T value) {
+ writer.writeString(text());
+ }
+
+ @Override
+ public final void writeUtf8(Utf8JsonWriter writer, T value) {
+ writer.writeString(text());
+ }
+
+ @Override
+ public final T readLatin1(Latin1JsonReader reader) {
+ reader.skipValue();
+ return value();
+ }
+
+ @Override
+ public final T readUtf16(Utf16JsonReader reader) {
+ reader.skipValue();
+ return value();
+ }
+
+ @Override
+ public final T readUtf8(Utf8JsonReader reader) {
+ reader.skipValue();
+ return value();
+ }
+ }
+
+ public static class StringArrayCodec extends ConstantCodec<String[]> {
+ @Override
+ protected String text() {
+ return "whole-array";
+ }
+
+ @Override
+ protected String[] value() {
+ return new String[] {"whole-array"};
+ }
+ }
+
+ public static class WholeMapCodec extends ConstantCodec<Map<String, String>> {
+ @Override
+ protected String text() {
+ return "whole-map";
+ }
+
+ @Override
+ protected Map<String, String> value() {
+ return new LinkedHashMap<>();
+ }
+ }
+
+ public static class WholeStringListCodec extends ConstantCodec<List<String>> {
+ @Override
+ protected String text() {
+ return "whole-explicit";
+ }
+
+ @Override
+ protected List<String> value() {
+ return new ArrayList<>();
+ }
+ }
+
+ public static class WholeDeclaredListCodec extends ConstantCodec<List<DeclaredValue>> {
+ @Override
+ protected String text() {
+ return "whole-default";
+ }
+
+ @Override
+ protected List<DeclaredValue> value() {
+ return new ArrayList<>();
+ }
+ }
+
+ public abstract static class PrecedenceCodec extends ConstantCodec<PrecedenceValue> {
+ private final String text;
+
+ protected PrecedenceCodec(String text) {
+ this.text = text;
+ }
+
+ @Override
+ protected final String text() {
+ return text;
+ }
+
+ @Override
+ protected PrecedenceValue value() {
+ return new PrecedenceValue();
+ }
+ }
+
+ public static class DeclaredPrecedenceCodec extends PrecedenceCodec {
+ public DeclaredPrecedenceCodec() {
+ super("declared");
+ }
+ }
+
+ public static class LocalPrecedenceCodec extends PrecedenceCodec {
+ public LocalPrecedenceCodec() {
+ super("local");
+ }
+ }
+
+ public static class BuilderPrecedenceCodec extends PrecedenceCodec {
+ public BuilderPrecedenceCodec() {
+ super("builder");
+ }
+ }
+
+ public static class BuilderChildCodec extends ConstantCodec<InheritedPrecedenceValue> {
+ @Override
+ protected String text() {
+ return "builder-child";
+ }
+
+ @Override
+ protected InheritedPrecedenceValue value() {
+ return new InheritedPrecedenceValue();
+ }
+ }
+
+ public static class DeclaredValueCodec extends ConstantCodec<DeclaredValue> {
+ @Override
+ protected String text() {
+ return "declared-value";
+ }
+
+ @Override
+ protected DeclaredValue value() {
+ return new DeclaredValue();
+ }
+ }
+
+ private static void writeTagged(JsonWriter writer, String value, String tag) {
+ if (value == null) {
+ writer.writeNull();
+ } else {
+ writer.writeString(tag + ':' + value);
+ }
+ }
+
+ private static String readTagged(JsonReader reader, String tag) {
+ String value = reader.readNullableString();
+ if (value == null) {
+ return null;
+ }
+ String prefix = tag + ':';
+ if (!value.startsWith(prefix)) {
+ throw new ForyJsonException("Expected " + prefix);
+ }
+ return value.substring(prefix.length());
+ }
+
+ private static ScalarKind readEnum(JsonReader reader) {
+ return ScalarKind.valueOf(readTagged(reader, "E"));
+ }
+
+ private static Value readValue(JsonReader reader) {
+ return new Value(readTagged(reader, "V"));
+ }
+
+ public static class RepresentationModel {
+ @JsonCodec(PathStringCodec.class)
+ public String value;
+ }
+
+ public static class MergedProperty {
+ @JsonCodec(AStringCodec.class)
+ private String value;
+
+ public @JsonCodec(AStringCodec.class) String getValue() {
+ return value;
+ }
+
+ public void setValue(@JsonCodec(AStringCodec.class) String value) {
+ this.value = value;
+ }
+ }
+
+ public static class ConflictingProperty {
+ @JsonCodec(AStringCodec.class)
+ private String value;
+
+ public @JsonCodec(BStringCodec.class) String getValue() {
+ return value;
+ }
+
+ public void setValue(@JsonCodec(AStringCodec.class) String value) {
+ this.value = value;
+ }
+ }
+
+ public static class PropertyListCreator {
+ @JsonCodec(AStringCodec.class)
+ public final String value;
+
+ @JsonCreator({"value"})
+ public PropertyListCreator(@JsonCodec(AStringCodec.class) String value) {
+ this.value = value;
+ }
+ }
+
+ public static class ParameterLocalCreator {
+ private final String value;
+
+ @JsonCreator
+ public ParameterLocalCreator(
+ @JsonProperty("value") @JsonCodec(AStringCodec.class) String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+ }
+
+ public static class CreatorOnly {
+ public transient String decoded;
+
+ @JsonCreator
+ public CreatorOnly(@JsonProperty("input") @JsonCodec(AStringCodec.class) String input) {
+ decoded = input;
+ }
+ }
+
+ public static class FieldAny {
+ @JsonAnyProperty
+ public Map<String, @JsonCodec(AStringCodec.class) String> values = new LinkedHashMap<>();
+ }
+
+ public static class MethodAny {
+ public transient Map<String, String> values = new LinkedHashMap<>();
+
+ @JsonAnyGetter
+ public Map<String, @JsonCodec(AStringCodec.class) String> any() {
+ return values;
+ }
+
+ @JsonAnySetter
+ public void put(String key, @JsonCodec(AStringCodec.class) String value) {
+ values.put(key, value);
+ }
+ }
+
+ public static class OuterAny {
+ @JsonAnyProperty
+ public @JsonCodec(WholeMapCodec.class) Map<String, String> values = new LinkedHashMap<>();
+ }
+
+ public static class KeyAny {
+ @JsonAnyProperty
+ public Map<@JsonCodec(AStringCodec.class) String, String> values = new LinkedHashMap<>();
+ }
+
+ public enum ScalarKind {
+ ONE,
+ TWO
+ }
+
+ public static class Value {
+ public String text;
+
+ public Value() {}
+
+ public Value(String text) {
+ this.text = text;
+ }
+ }
+
+ public static class ScalarModel {
+ @JsonCodec(IntCodec.class)
+ public int number;
+
+ @JsonCodec(AStringCodec.class)
+ public String text;
+
+ @JsonCodec(EnumCodec.class)
+ public ScalarKind kind;
+
+ @JsonCodec(ValueCodec.class)
+ public Value object;
+ }
+
+ public static class WholeArray {
+ public String @JsonCodec(StringArrayCodec.class) [] value;
+ }
+
+ public static class ComponentArray {
+ public @JsonCodec(AStringCodec.class) String[] value;
+ }
+
+ public static class MultiArray {
+ public @JsonCodec(AStringCodec.class) String[][] value;
+ }
+
+ public static class ListModel {
+ public List<@JsonCodec(AStringCodec.class) String> value;
+ }
+
+ public static class SetModel {
+ public Set<@JsonCodec(AStringCodec.class) String> value;
+ }
+
+ public static class CollectionModel {
+ public Collection<@JsonCodec(AStringCodec.class) String> value;
+ }
+
+ public static class ConcreteListModel {
+ public ArrayList<@JsonCodec(AStringCodec.class) String> value;
+ }
+
+ public static class ReorderedList<K, V> extends ArrayList<V> {}
+
+ public static class ReorderedListModel {
+ public ReorderedList<Integer, @JsonCodec(AStringCodec.class) String> value;
+ }
+
+ public static class MapModel {
+ public Map<String, @JsonCodec(AStringCodec.class) String> values = new LinkedHashMap<>();
+ }
+
+ public static class MapKeyModel {
+ public Map<@JsonCodec(AStringCodec.class) String, String> values = new LinkedHashMap<>();
+ }
+
+ public static class OptionalModel {
+ public Optional<@JsonCodec(AStringCodec.class) String> value;
+ }
+
+ public static class AtomicModel {
+ public AtomicReference<@JsonCodec(AStringCodec.class) String> value;
+ }
+
+ public static class AtomicArrayModel {
+ public AtomicReferenceArray<@JsonCodec(AStringCodec.class) String> value;
+ }
+
+ public static class Envelope<T> {
+ public T value;
+ }
+
+ public static class EnvelopeOwner {
+ public Envelope<@JsonCodec(AStringCodec.class) String> envelope;
+ }
+
+ public static class AnnotatedEnvelope<T> {
+ public @JsonCodec(AStringCodec.class) T value;
+ }
+
+ public static class EqualEnvelopeOwner {
+ public AnnotatedEnvelope<@JsonCodec(AStringCodec.class) String> envelope;
+ }
+
+ public static class ConflictingEnvelopeOwner {
+ public AnnotatedEnvelope<@JsonCodec(BStringCodec.class) String> envelope;
+ }
+
+ @SuppressWarnings("rawtypes")
+ public static class RawEnvelopeOwner {
+ public AnnotatedEnvelope envelope;
+ }
+
+ public static class CacheModel {
+ public String plain;
+
+ @JsonCodec(AStringCodec.class)
+ public String a;
+
+ @JsonCodec(AStringCodec.class)
+ public String sameA;
+
+ @JsonCodec(BStringCodec.class)
+ public String b;
+ }
+
+ @JsonCodec(DeclaredPrecedenceCodec.class)
+ public static class PrecedenceValue {}
+
+ public static class InheritedPrecedenceValue extends PrecedenceValue {}
+
+ public static class PrecedenceHolder {
+ public @JsonCodec(LocalPrecedenceCodec.class) PrecedenceValue local;
+ public PrecedenceValue regular;
+ }
+
+ public static class InheritedPrecedenceHolder {
+ public @JsonCodec(LocalPrecedenceCodec.class) InheritedPrecedenceValue local;
+ public InheritedPrecedenceValue regular;
+ }
+
+ public static class HiddenExplicit {
+ public @JsonCodec(WholeStringListCodec.class) List<@JsonCodec(AStringCodec.class) String>
+ values;
+ }
+
+ @JsonCodec(DeclaredValueCodec.class)
+ public static class DeclaredValue {}
+
+ public static class HiddenDefault {
+ public @JsonCodec(WholeDeclaredListCodec.class) List<DeclaredValue> values;
+ }
+}
diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonCodecHierarchyTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonCodecHierarchyTest.java
new file mode 100644
index 000000000..a1c86f2a0
--- /dev/null
+++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonCodecHierarchyTest.java
@@ -0,0 +1,833 @@
+/*
+ * 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.assertNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Stream;
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
+import org.apache.fory.exception.InsecureException;
+import org.apache.fory.json.annotation.JsonCodec;
+import org.apache.fory.json.annotation.JsonSubTypes;
+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.testng.SkipException;
+import org.testng.annotations.Test;
+
+public class JsonCodecHierarchyTest extends ForyJsonTestModels {
+ @Test
+ public void directRoots() {
+ ForyJson json = newJson();
+ assertMarker(json, new DirectValue(), "direct");
+ assertMarker(json, DirectEnum.VALUE, "enum");
+ assertEquals(json.toJson(new DirectImplementation(), DirectContract.class), "\"interface\"");
+ assertMarker(json, new DirectImplementation(), "interface");
+ assertMarker(json, new DirectList(), "collection");
+ assertMarker(json, new InheritedList(), "inherited-collection");
+ }
+
+ @Test
+ public void recordRoot() throws Exception {
+ if (JdkVersion.MAJOR_VERSION < 17) {
+ throw new SkipException("Java record test requires JDK 17+");
+ }
+ Class<?> type =
+ compileRecordClass(
+ "JsonCodecAnnotatedRecord",
+ "package org.apache.fory.json.records;\n"
+ + "import org.apache.fory.json.annotation.JsonCodec;\n"
+ + "import org.apache.fory.json.JsonCodecHierarchyTest.RecordCodec;\n"
+ + "@JsonCodec(RecordCodec.class)\n"
+ + "public record JsonCodecAnnotatedRecord(int value) {}\n");
+ Object value = type.getConstructor(int.class).newInstance(1);
+ assertMarker(newJson(), value, "record");
+ }
+
+ @Test
+ public void inheritsDeclarations() {
+ ForyJson json = newJson();
+ assertMarker(json, new ChildValue(), "a");
+ assertMarker(json, new InheritedImplementation(), "interface-a");
+ }
+
+ @Test
+ public void sameInterfaces() {
+ ForyJson json = newJson();
+ assertMarker(json, new SameOrderLeft(), "a");
+ assertMarker(json, new SameOrderRight(), "a");
+ }
+
+ @Test
+ public void interfaceOrder() throws Exception {
+ try (LoadedType leftFirst = compileConflictType("LeftConflict, RightConflict");
+ LoadedType rightFirst = compileConflictType("RightConflict, LeftConflict")) {
+ ForyJson json = newJson();
+ String leftMessage = conflictMessage(json, leftFirst.newInstance());
+ String rightMessage = conflictMessage(json, rightFirst.newInstance());
+ assertEquals(leftMessage, rightMessage);
+ assertTrue(
+ leftMessage.contains(LeftConflict.class.getName() + " -> " + ACodec.class.getName()));
+ assertTrue(
+ leftMessage.contains(RightConflict.class.getName() + " -> " + BCodec.class.getName()));
+ }
+ }
+
+ @Test
+ public void specificDeclarations() {
+ ForyJson json = newJson();
+ assertMarker(json, new DiamondValue(), "a");
+ assertMarker(json, new SpecificValue(), "child-interface");
+ assertMarker(json, new ClassOverride(), "child-class");
+ }
+
+ @Test
+ public void classInterface() {
+ ForyJson json = newJson();
+ assertMarker(json, new RelatedChild(), "related-class");
+ assertMarker(json, new SameClassInterface(), "a");
+ String message = conflictMessage(json, new UnrelatedClassInterface());
+ assertTrue(message.contains(ParentValue.class.getName() + " -> " + ACodec.class.getName()));
+ assertTrue(
+ message.contains(UnrelatedInterface.class.getName() + " -> " + BCodec.class.getName()));
+ }
+
+ @Test
+ public void disambiguation() {
+ ForyJson json = newJson();
+ assertMarker(json, new DirectConflict(), "direct-conflict");
+
+ RuntimeMarkerCodec<BuilderConflict> codec = new RuntimeMarkerCodec<>("builder-conflict");
+ json = newJsonBuilder().registerCodec(BuilderConflict.class, codec).build();
+ assertMarker(json, new BuilderConflict(), "builder-conflict");
+
+ RuntimeMarkerCodec<DirectValue> directCodec = new RuntimeMarkerCodec<>("builder-direct");
+ json = newJsonBuilder().registerCodec(DirectValue.class, directCodec).build();
+ assertMarker(json, new DirectValue(), "builder-direct");
+ }
+
+ @Test
+ public void builderIsExact() {
+ RuntimeMarkerCodec<ParentValue> codec = new RuntimeMarkerCodec<>("registered-parent");
+ ForyJson json = newJsonBuilder().registerCodec(ParentValue.class, codec).build();
+ assertMarker(json, new ParentValue(), "registered-parent");
+ assertMarker(json, new ChildValue(), "a");
+ }
+
+ @Test
+ public void subtypePrecedence() {
+ ForyJson json = newJson();
+ assertEquals(json.toJson(new SubTypeValue(), SubTypeContract.class), "\"subtypes\"");
+ assertMarker(json, new SubTypeValue(), "subtypes");
+ }
+
+ @Test
+ public void inheritedResults() {
+ ForyJson json = newJson();
+ String latinJson = "\"latin\"";
+ assertEquals(
+ json.fromJson(latinJson, ReadChild.class).reader,
+ JsonTestSupport.stringReaderPath(latinJson));
+ assertEquals(json.fromJson("\"你好\"", ReadChild.class).reader, "utf16");
+ assertEquals(
+ json.fromJson("\"utf8\"".getBytes(StandardCharsets.UTF_8), ReadChild.class).reader, "utf8");
+
+ assertNull(json.fromJson("\"latin\"", NullChild.class));
+ assertNull(json.fromJson("\"你好\"", NullChild.class));
+ assertNull(json.fromJson("null".getBytes(StandardCharsets.UTF_8), NullChild.class));
+ }
+
+ @Test
+ public void incompatibleResults() {
+ ForyJson json = newJson();
+ assertIncompatible(() -> json.fromJson("\"latin\"", IncompatibleChild.class));
+ assertIncompatible(() -> json.fromJson("\"你好\"", IncompatibleChild.class));
+ assertIncompatible(
+ () -> json.fromJson("\"utf8\"".getBytes(StandardCharsets.UTF_8), IncompatibleChild.class));
+ }
+
+ @Test
+ public void invalidCodecs() {
+ assertInvalid(PrivateCodecValue.class, PrivateCodec.class, "must be public");
+ assertInvalid(AbstractCodecValue.class, AbstractCodec.class, "must be concrete");
+ assertInvalid(NoDefaultCodecValue.class, NoDefaultCodec.class, "public no-argument");
+ assertInvalid(MemberCodecValue.class, MemberCodec.class, "top-level or a static nested class");
+ assertInvalid(ThrowingCodecValue.class, ThrowingCodec.class, "constructor failed");
+ }
+
+ @Test
+ public void codecReuse() {
+ CountingCodec.CONSTRUCTIONS.set(0);
+ ForyJson json = newJson();
+ assertMarker(json, new CountedValueA(), "counted");
+ assertMarker(json, new CountedValueB(), "counted");
+ assertMarker(json, new CountedValueA(), "counted");
+ assertEquals(CountingCodec.CONSTRUCTIONS.get(), 1);
+
+ assertMarker(newJson(), new CountedValueA(), "counted");
+ assertEquals(CountingCodec.CONSTRUCTIONS.get(), 2);
+ }
+
+ @Test
+ public void concurrentCodecReuse() throws Exception {
+ CountingCodec.CONSTRUCTIONS.set(0);
+ ForyJson json = newJson();
+ ExecutorService executor = Executors.newFixedThreadPool(8);
+ try {
+ List<Future<String>> results = new ArrayList<>();
+ for (int i = 0; i < 32; i++) {
+ final boolean first = (i & 1) == 0;
+ results.add(
+ executor.submit(() -> json.toJson(first ? new CountedValueA() : new CountedValueB())));
+ }
+ for (Future<String> result : results) {
+ assertEquals(result.get(), "\"counted\"");
+ }
+ } finally {
+ executor.shutdownNow();
+ }
+ assertEquals(CountingCodec.CONSTRUCTIONS.get(), 1);
+ }
+
+ @Test
+ public void securityPrecedesConstruction() {
+ CountingCodec.CONSTRUCTIONS.set(0);
+ ForyJson json =
+ newJsonBuilder()
+ .withTypeChecker(
+ (className, context) -> !className.equals(CountedValueA.class.getName()))
+ .build();
+ try {
+ json.toJson(new CountedValueA());
+ fail("Expected annotated target rejection");
+ } catch (InsecureException expected) {
+ assertEquals(CountingCodec.CONSTRUCTIONS.get(), 0);
+ }
+ }
+
+ private static void assertMarker(ForyJson json, Object value, String marker) {
+ String expected = '"' + marker + '"';
+ assertEquals(json.toJson(value), expected);
+ assertEquals(new String(json.toJsonBytes(value), StandardCharsets.UTF_8), expected);
+ }
+
+ private static String conflictMessage(ForyJson json, Object value) {
+ try {
+ json.toJson(value);
+ fail("Expected an inherited @JsonCodec conflict");
+ return null;
+ } catch (ForyJsonException e) {
+ return e.getMessage();
+ }
+ }
+
+ private static void assertIncompatible(ReadCall call) {
+ try {
+ call.read();
+ fail("Expected an incompatible inherited codec result");
+ } catch (ForyJsonException e) {
+ String message = e.getMessage();
+ assertTrue(message.contains(IncompatibleCodec.class.getName()));
+ assertTrue(message.contains(IncompatibleParent.class.getName()));
+ assertTrue(message.contains(IncompatibleChild.class.getName()));
+ assertTrue(message.contains("expected null or a value assignable"));
+ }
+ }
+
+ private static void assertInvalid(
+ Class<?> valueType, Class<? extends JsonValueCodec<?>> codecType, String reason) {
+ try {
+ ForyJson.builder().withCodegen(false).build().toJson(newValue(valueType));
+ fail("Expected an invalid @JsonCodec class");
+ } catch (ForyJsonException e) {
+ assertTrue(e.getMessage().contains(codecType.getName()));
+ assertTrue(e.getMessage().contains(reason));
+ }
+ }
+
+ private static Object newValue(Class<?> type) {
+ try {
+ return type.getConstructor().newInstance();
+ } catch (ReflectiveOperationException e) {
+ throw new AssertionError(e);
+ }
+ }
+
+ private static LoadedType compileConflictType(String interfaces) throws Exception {
+ JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+ if (compiler == null) {
+ throw new SkipException("A JDK compiler is required");
+ }
+ Path root = Files.createTempDirectory("fory-json-codec-order");
+ Path output = root.resolve("classes");
+ Path source = root.resolve("src/org/apache/fory/json/hierarchy/ConflictValue.java");
+ Files.createDirectories(output);
+ Files.createDirectories(source.getParent());
+ String text =
+ "package org.apache.fory.json.hierarchy;\n"
+ + "import org.apache.fory.json.JsonCodecHierarchyTest.LeftConflict;\n"
+ + "import org.apache.fory.json.JsonCodecHierarchyTest.RightConflict;\n"
+ + "public final class ConflictValue implements "
+ + interfaces
+ + " {}\n";
+ Files.write(source, text.getBytes(StandardCharsets.UTF_8));
+ int exit =
+ compiler.run(
+ null,
+ null,
+ null,
+ "-classpath",
+ System.getProperty("java.class.path"),
+ "-d",
+ output.toString(),
+ source.toString());
+ assertEquals(exit, 0);
+ URLClassLoader loader =
+ new URLClassLoader(
+ new URL[] {output.toUri().toURL()}, JsonCodecHierarchyTest.class.getClassLoader());
+ Class<?> type = Class.forName("org.apache.fory.json.hierarchy.ConflictValue", true, loader);
+ return new LoadedType(root, loader, type);
+ }
+
+ private static final class LoadedType implements AutoCloseable {
+ private final Path root;
+ private final URLClassLoader loader;
+ private final Class<?> type;
+
+ private LoadedType(Path root, URLClassLoader loader, Class<?> type) {
+ this.root = root;
+ this.loader = loader;
+ this.type = type;
+ }
+
+ private Object newInstance() throws ReflectiveOperationException {
+ return type.getConstructor().newInstance();
+ }
+
+ @Override
+ public void close() throws Exception {
+ loader.close();
+ try (Stream<Path> files = Files.walk(root)) {
+ files
+ .sorted(Comparator.reverseOrder())
+ .forEach(
+ path -> {
+ try {
+ Files.deleteIfExists(path);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ });
+ }
+ }
+ }
+
+ private interface ReadCall {
+ Object read();
+ }
+
+ public abstract static class MarkerCodec implements JsonValueCodec<Object> {
+ protected abstract String marker();
+
+ @Override
+ public final void writeString(StringJsonWriter writer, Object value) {
+ writeStringValue(writer, value, marker());
+ }
+
+ @Override
+ public final void writeUtf8(Utf8JsonWriter writer, Object value) {
+ writeUtf8Value(writer, value, marker());
+ }
+
+ @Override
+ public Object readLatin1(Latin1JsonReader reader) {
+ reader.skipValue();
+ return null;
+ }
+
+ @Override
+ public Object readUtf16(Utf16JsonReader reader) {
+ reader.skipValue();
+ return null;
+ }
+
+ @Override
+ public Object readUtf8(Utf8JsonReader reader) {
+ reader.skipValue();
+ return null;
+ }
+ }
+
+ public static class ACodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "a";
+ }
+ }
+
+ public static class BCodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "b";
+ }
+ }
+
+ public static class DirectCodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "direct";
+ }
+ }
+
+ public static class EnumCodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "enum";
+ }
+ }
+
+ public static class InterfaceCodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "interface";
+ }
+ }
+
+ public static class CollectionMarkerCodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "collection";
+ }
+ }
+
+ public static class InheritedCollectionCodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "inherited-collection";
+ }
+ }
+
+ public static class RecordCodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "record";
+ }
+ }
+
+ public static class InterfaceACodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "interface-a";
+ }
+ }
+
+ public static class ChildInterfaceCodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "child-interface";
+ }
+ }
+
+ public static class ChildClassCodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "child-class";
+ }
+ }
+
+ public static class RelatedClassCodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "related-class";
+ }
+ }
+
+ public static class DirectConflictCodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "direct-conflict";
+ }
+ }
+
+ public static class SubTypesCodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "subtypes";
+ }
+ }
+
+ public static class CountingCodec extends MarkerCodec {
+ private static final AtomicInteger CONSTRUCTIONS = new AtomicInteger();
+
+ public CountingCodec() {
+ CONSTRUCTIONS.incrementAndGet();
+ }
+
+ @Override
+ protected String marker() {
+ return "counted";
+ }
+ }
+
+ private static final class RuntimeMarkerCodec<T> implements JsonValueCodec<T> {
+ private final String marker;
+
+ private RuntimeMarkerCodec(String marker) {
+ this.marker = marker;
+ }
+
+ @Override
+ public void writeString(StringJsonWriter writer, T value) {
+ writeStringValue(writer, value, marker);
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, T value) {
+ writeUtf8Value(writer, value, marker);
+ }
+
+ @Override
+ public T readLatin1(Latin1JsonReader reader) {
+ reader.skipValue();
+ return null;
+ }
+
+ @Override
+ public T readUtf16(Utf16JsonReader reader) {
+ reader.skipValue();
+ return null;
+ }
+
+ @Override
+ public T readUtf8(Utf8JsonReader reader) {
+ reader.skipValue();
+ return null;
+ }
+ }
+
+ public static class AssignableCodec implements JsonValueCodec<ReadParent> {
+ @Override
+ public void writeString(StringJsonWriter writer, ReadParent value) {
+ writeStringValue(writer, value, "read");
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, ReadParent value) {
+ writeUtf8Value(writer, value, "read");
+ }
+
+ @Override
+ public ReadParent readLatin1(Latin1JsonReader reader) {
+ reader.skipValue();
+ return new ReadChild("latin1");
+ }
+
+ @Override
+ public ReadParent readUtf16(Utf16JsonReader reader) {
+ reader.skipValue();
+ return new ReadChild("utf16");
+ }
+
+ @Override
+ public ReadParent readUtf8(Utf8JsonReader reader) {
+ reader.skipValue();
+ return new ReadChild("utf8");
+ }
+ }
+
+ public static class NullCodec implements JsonValueCodec<NullParent> {
+ @Override
+ public void writeString(StringJsonWriter writer, NullParent value) {
+ writer.writeNull();
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, NullParent value) {
+ writer.writeNull();
+ }
+
+ @Override
+ public NullParent readLatin1(Latin1JsonReader reader) {
+ reader.skipValue();
+ return null;
+ }
+
+ @Override
+ public NullParent readUtf16(Utf16JsonReader reader) {
+ reader.skipValue();
+ return null;
+ }
+
+ @Override
+ public NullParent readUtf8(Utf8JsonReader reader) {
+ reader.skipValue();
+ return null;
+ }
+ }
+
+ public static class IncompatibleCodec implements JsonValueCodec<IncompatibleParent> {
+ @Override
+ public void writeString(StringJsonWriter writer, IncompatibleParent value) {
+ writeStringValue(writer, value, "incompatible");
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, IncompatibleParent value) {
+ writeUtf8Value(writer, value, "incompatible");
+ }
+
+ @Override
+ public IncompatibleParent readLatin1(Latin1JsonReader reader) {
+ reader.skipValue();
+ return new IncompatibleParent();
+ }
+
+ @Override
+ public IncompatibleParent readUtf16(Utf16JsonReader reader) {
+ reader.skipValue();
+ return new IncompatibleParent();
+ }
+
+ @Override
+ public IncompatibleParent readUtf8(Utf8JsonReader reader) {
+ reader.skipValue();
+ return new IncompatibleParent();
+ }
+ }
+
+ private static void writeStringValue(StringJsonWriter writer, Object value, String marker) {
+ if (value == null) {
+ writer.writeNull();
+ } else {
+ writer.writeString(marker);
+ }
+ }
+
+ private static void writeUtf8Value(Utf8JsonWriter writer, Object value, String marker) {
+ if (value == null) {
+ writer.writeNull();
+ } else {
+ writer.writeString(marker);
+ }
+ }
+
+ @JsonCodec(DirectCodec.class)
+ public static class DirectValue {}
+
+ @JsonCodec(EnumCodec.class)
+ public enum DirectEnum {
+ VALUE
+ }
+
+ @JsonCodec(InterfaceCodec.class)
+ public interface DirectContract {}
+
+ public static class DirectImplementation implements DirectContract {}
+
+ @JsonCodec(CollectionMarkerCodec.class)
+ public static class DirectList extends ArrayList<String> {}
+
+ @JsonCodec(InheritedCollectionCodec.class)
+ public interface InheritedCollectionContract {}
+
+ public static class InheritedList extends ArrayList<String>
+ implements InheritedCollectionContract {}
+
+ @JsonCodec(ACodec.class)
+ public static class ParentValue {}
+
+ public static class ChildValue extends ParentValue {}
+
+ @JsonCodec(InterfaceACodec.class)
+ public interface InheritedContract {}
+
+ public static class InheritedImplementation implements InheritedContract {}
+
+ @JsonCodec(ACodec.class)
+ public interface SameInterfaceA {}
+
+ @JsonCodec(ACodec.class)
+ public interface SameInterfaceB {}
+
+ public static class SameOrderLeft implements SameInterfaceA, SameInterfaceB {}
+
+ public static class SameOrderRight implements SameInterfaceB, SameInterfaceA {}
+
+ @JsonCodec(ACodec.class)
+ public interface LeftConflict {}
+
+ @JsonCodec(BCodec.class)
+ public interface RightConflict {}
+
+ @JsonCodec(ACodec.class)
+ public interface DiamondRoot {}
+
+ public interface DiamondLeft extends DiamondRoot {}
+
+ public interface DiamondRight extends DiamondRoot {}
+
+ public static class DiamondValue implements DiamondLeft, DiamondRight {}
+
+ @JsonCodec(ACodec.class)
+ public interface SpecificParent {}
+
+ @JsonCodec(ChildInterfaceCodec.class)
+ public interface SpecificChild extends SpecificParent {}
+
+ public static class SpecificValue implements SpecificChild {}
+
+ @JsonCodec(ACodec.class)
+ public static class ClassParent {}
+
+ @JsonCodec(ChildClassCodec.class)
+ public static class ClassOverride extends ClassParent {}
+
+ @JsonCodec(ACodec.class)
+ public interface RelatedInterface {}
+
+ @JsonCodec(RelatedClassCodec.class)
+ public static class RelatedParent implements RelatedInterface {}
+
+ public static class RelatedChild extends RelatedParent {}
+
+ @JsonCodec(ACodec.class)
+ public interface SameClassInterfaceContract {}
+
+ public static class SameClassInterface extends ParentValue
+ implements SameClassInterfaceContract {}
+
+ @JsonCodec(BCodec.class)
+ public interface UnrelatedInterface {}
+
+ public static class UnrelatedClassInterface extends ParentValue implements UnrelatedInterface {}
+
+ @JsonCodec(DirectConflictCodec.class)
+ public static class DirectConflict extends ParentValue implements UnrelatedInterface {}
+
+ public static class BuilderConflict extends ParentValue implements UnrelatedInterface {}
+
+ @JsonCodec(SubTypesCodec.class)
+ @JsonSubTypes(
+ value = @JsonSubTypes.Type(name = "value", value = SubTypeValue.class),
+ inclusion = JsonSubTypes.Inclusion.WRAPPER_ARRAY)
+ public interface SubTypeContract {}
+
+ public static class SubTypeValue implements SubTypeContract {}
+
+ @JsonCodec(AssignableCodec.class)
+ public static class ReadParent {}
+
+ public static class ReadChild extends ReadParent {
+ private final String reader;
+
+ public ReadChild(String reader) {
+ this.reader = reader;
+ }
+ }
+
+ @JsonCodec(NullCodec.class)
+ public static class NullParent {}
+
+ public static class NullChild extends NullParent {}
+
+ @JsonCodec(IncompatibleCodec.class)
+ public static class IncompatibleParent {}
+
+ public static class IncompatibleChild extends IncompatibleParent {}
+
+ @JsonCodec(PrivateCodec.class)
+ public static class PrivateCodecValue {}
+
+ private static class PrivateCodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "private";
+ }
+ }
+
+ @JsonCodec(AbstractCodec.class)
+ public static class AbstractCodecValue {}
+
+ public abstract static class AbstractCodec extends MarkerCodec {}
+
+ @JsonCodec(NoDefaultCodec.class)
+ public static class NoDefaultCodecValue {}
+
+ public static class NoDefaultCodec extends MarkerCodec {
+ public NoDefaultCodec(String ignored) {}
+
+ @Override
+ protected String marker() {
+ return "no-default";
+ }
+ }
+
+ @JsonCodec(MemberCodec.class)
+ public static class MemberCodecValue {}
+
+ public class MemberCodec extends MarkerCodec {
+ @Override
+ protected String marker() {
+ return "member";
+ }
+ }
+
+ @JsonCodec(ThrowingCodec.class)
+ public static class ThrowingCodecValue {}
+
+ public static class ThrowingCodec extends MarkerCodec {
+ public ThrowingCodec() {
+ throw new IllegalStateException("expected");
+ }
+
+ @Override
+ protected String marker() {
+ return "throwing";
+ }
+ }
+
+ @JsonCodec(CountingCodec.class)
+ public static class CountedValueA {}
+
+ @JsonCodec(CountingCodec.class)
+ public static class CountedValueB {}
+}
diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonScalarTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonScalarTest.java
index cd48584fa..0dd8f260c 100644
--- a/java/fory-json/src/test/java/org/apache/fory/json/JsonScalarTest.java
+++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonScalarTest.java
@@ -77,7 +77,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
-import org.apache.fory.json.codec.JsonCodec;
+import org.apache.fory.json.codec.JsonValueCodec;
import org.apache.fory.json.data.BoxedScalars;
import org.apache.fory.json.data.CoreScalarFields;
import org.apache.fory.json.data.JsonTestData;
@@ -2739,7 +2739,7 @@ public class JsonScalarTest extends ForyJsonTestModels {
field.setInt(owner, value);
}
- private static final class UrlStringCodec implements JsonCodec<URL> {
+ private static final class UrlStringCodec implements JsonValueCodec<URL> {
@Override
public void writeString(StringJsonWriter writer, URL value) {
if (value == null) {
@@ -2797,7 +2797,7 @@ public class JsonScalarTest extends ForyJsonTestModels {
public Map<String, NullOwnedValue> map;
}
- private static final class NullOwnedValueCodec implements JsonCodec<NullOwnedValue> {
+ private static final class NullOwnedValueCodec implements JsonValueCodec<NullOwnedValue> {
@Override
public void writeString(StringJsonWriter writer, NullOwnedValue value) {
writer.writeString(value == null ? "string-null" : value.mode);
@@ -2833,7 +2833,7 @@ public class JsonScalarTest extends ForyJsonTestModels {
}
}
- private static final class ModeAwareCodec implements JsonCodec<ModeAwareValue> {
+ private static final class ModeAwareCodec implements JsonValueCodec<ModeAwareValue> {
@Override
public void writeString(StringJsonWriter writer, ModeAwareValue value) {
writer.writeNull();
@@ -2863,7 +2863,7 @@ public class JsonScalarTest extends ForyJsonTestModels {
}
}
- private static final class TaggedNumberCodec<T extends Number> implements JsonCodec<T> {
+ private static final class TaggedNumberCodec<T extends Number> implements JsonValueCodec<T> {
private final String token;
private final T decoded;
@@ -2901,7 +2901,7 @@ public class JsonScalarTest extends ForyJsonTestModels {
}
}
- private static final class TaggedStringCodec implements JsonCodec<String> {
+ private static final class TaggedStringCodec implements JsonValueCodec<String> {
private final String token;
private final String decoded;
diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonSubTypesTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonSubTypesTest.java
index 89ecd04ba..4074098d0 100644
--- a/java/fory-json/src/test/java/org/apache/fory/json/JsonSubTypesTest.java
+++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonSubTypesTest.java
@@ -32,7 +32,7 @@ import java.util.List;
import org.apache.fory.json.annotation.JsonPropertyOrder;
import org.apache.fory.json.annotation.JsonSubTypes;
import org.apache.fory.json.annotation.JsonSubTypes.Inclusion;
-import org.apache.fory.json.codec.JsonCodec;
+import org.apache.fory.json.codec.JsonValueCodec;
import org.apache.fory.json.meta.JsonSubtypeScanInfo;
import org.apache.fory.json.reader.JsonReader;
import org.apache.fory.json.reader.Latin1JsonReader;
@@ -352,7 +352,7 @@ public class JsonSubTypesTest extends ForyJsonTestModels {
}
}
- private static final class WrappedValueCodec implements JsonCodec<WrappedValue> {
+ private static final class WrappedValueCodec implements JsonValueCodec<WrappedValue> {
@Override
public void writeString(StringJsonWriter writer, WrappedValue value) {
writer.writeString(value.text);
@@ -389,7 +389,7 @@ public class JsonSubTypesTest extends ForyJsonTestModels {
}
}
- private static final class ArrayWrappedValueCodec implements JsonCodec<ArrayWrappedValue> {
+ private static final class ArrayWrappedValueCodec implements JsonValueCodec<ArrayWrappedValue> {
@Override
public void writeString(StringJsonWriter writer, ArrayWrappedValue value) {
writer.writeString(value.text);
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 8582b4495..1a95060b4 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
@@ -22,7 +22,7 @@ package org.apache.fory.json;
import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
-import org.apache.fory.json.codec.JsonCodec;
+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;
@@ -31,6 +31,7 @@ import org.apache.fory.json.resolver.JsonSharedRegistry;
import org.apache.fory.json.resolver.JsonTypeResolver;
import org.apache.fory.json.writer.StringJsonWriter;
import org.apache.fory.json.writer.Utf8JsonWriter;
+import org.apache.fory.serializer.StringSerializer;
final class JsonTestSupport {
private static final JsonConfig CONFIG =
@@ -47,8 +48,8 @@ final class JsonTestSupport {
new CodecRegistry(),
null);
private static final JsonSharedRegistry REGISTRY = new JsonSharedRegistry(CONFIG);
- private static final JsonCodec<Object> NULL_CODEC =
- new JsonCodec<Object>() {
+ private static final JsonValueCodec<Object> NULL_CODEC =
+ new JsonValueCodec<Object>() {
@Override
public void writeString(StringJsonWriter writer, Object value) {
writer.writeNull();
@@ -115,8 +116,8 @@ final class JsonTestSupport {
}
@SuppressWarnings("unchecked")
- static <T> JsonCodec<T> nullCodec() {
- return (JsonCodec<T>) NULL_CODEC;
+ static <T> JsonValueCodec<T> nullCodec() {
+ return (JsonValueCodec<T>) NULL_CODEC;
}
static JsonTypeResolver primaryTypeResolver(ForyJson json) {
@@ -142,6 +143,13 @@ final class JsonTestSupport {
}
}
+ static String stringReaderPath(String input) {
+ return StringSerializer.isBytesBackedString()
+ && StringSerializer.isLatin1Coder(StringSerializer.getStringCoder(input))
+ ? "latin1"
+ : "utf16";
+ }
+
static int pooledStateCount(ForyJson json) {
try {
return ((AtomicReferenceArray<?>) field(json, "slots")).length() + 1;
diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonTypeCheckerTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonTypeCheckerTest.java
index 4ebdfc339..86be77de6 100644
--- a/java/fory-json/src/test/java/org/apache/fory/json/JsonTypeCheckerTest.java
+++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonTypeCheckerTest.java
@@ -27,11 +27,13 @@ import java.beans.Expression;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.fory.exception.InsecureException;
-import org.apache.fory.json.codec.JsonCodec;
+import org.apache.fory.json.annotation.JsonCodec;
+import org.apache.fory.json.codec.JsonValueCodec;
import org.apache.fory.json.data.Kind;
import org.apache.fory.reflect.TypeRef;
import org.apache.fory.type.Float16;
@@ -39,7 +41,7 @@ import org.testng.annotations.Factory;
import org.testng.annotations.Test;
public class JsonTypeCheckerTest extends ForyJsonTestModels {
- private static final JsonCodec<String> STRING_NULL_CODEC = nullCodec();
+ private static final JsonValueCodec<String> STRING_NULL_CODEC = nullCodec();
@Factory(dataProvider = "enableCodegen")
public JsonTypeCheckerTest(boolean codegen) {
@@ -97,6 +99,31 @@ public class JsonTypeCheckerTest extends ForyJsonTestModels {
assertThrows(InsecureException.class, () -> json.toJson("value"));
}
+ @Test
+ public void annotatedExactUsesChecker() {
+ CountingStringCodec.CONSTRUCTIONS.set(0);
+ AnnotatedStringHolder value = new AnnotatedStringHolder();
+ ForyJson json = rejectingJson(String.class);
+ assertThrows(InsecureException.class, () -> json.toJson(value));
+ assertEquals(CountingStringCodec.CONSTRUCTIONS.get(), 0);
+ }
+
+ @Test
+ public void mapKeyIgnoresValueCodec() {
+ ForyJson json =
+ newJsonBuilder()
+ .registerCodec(String.class, STRING_NULL_CODEC)
+ .withTypeChecker((className, context) -> !className.equals(String.class.getName()))
+ .build();
+ StringKeyMap value = new StringKeyMap();
+ value.values = new LinkedHashMap<>();
+ value.values.put("key", 1);
+ assertEquals(json.toJson(value), "{\"values\":{\"key\":1}}");
+ assertEquals(
+ json.fromJson("{\"values\":{\"key\":2}}", StringKeyMap.class).values.get("key"),
+ Integer.valueOf(2));
+ }
+
@Test
public void customPrimitiveUsesChecker() {
ForyJson json =
@@ -236,6 +263,27 @@ public class JsonTypeCheckerTest extends ForyJsonTestModels {
public RejectedValue value;
}
+ public static final class StringKeyMap {
+ public Map<String, Integer> values;
+ }
+
+ public static final class AnnotatedStringHolder {
+ public @JsonCodec(CountingStringCodec.class) String value = "value";
+ }
+
+ public static final class CountingStringCodec extends JsonCodecAnnotationTest.TaggedStringCodec {
+ private static final AtomicInteger CONSTRUCTIONS = new AtomicInteger();
+
+ public CountingStringCodec() {
+ CONSTRUCTIONS.incrementAndGet();
+ }
+
+ @Override
+ protected String tag() {
+ return "checked";
+ }
+ }
+
public static final class ClassMembers {
public Class<?> type = String.class;
diff --git a/java/fory-json/src/test/java/org/apache/fory/json/meta/JsonTypeUseTest.java b/java/fory-json/src/test/java/org/apache/fory/json/meta/JsonTypeUseTest.java
new file mode 100644
index 000000000..bb4798650
--- /dev/null
+++ b/java/fory-json/src/test/java/org/apache/fory/json/meta/JsonTypeUseTest.java
@@ -0,0 +1,174 @@
+/*
+ * 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.meta;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertThrows;
+import static org.testng.Assert.assertTrue;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.fory.json.ForyJsonException;
+import org.apache.fory.json.annotation.JsonCodec;
+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.Test;
+
+public class JsonTypeUseTest {
+ @Test
+ public void testNestedExtraction() throws Exception {
+ JsonTypeUse values = typeUse("values");
+ assertEquals(values.rawType(), List.class);
+ assertFalse(values.hasCodec());
+ assertTrue(values.hasExplicitCodec());
+ assertEquals(values.argument(0).codecClass(), ACodec.class);
+ assertEquals(values.argument(0).rawType(), String.class);
+
+ JsonTypeUse array = typeUse("array");
+ assertEquals(array.codecClass(), ACodec.class);
+ assertNull(array.arrayComponent().codecClass());
+
+ JsonTypeUse elements = typeUse("elements");
+ assertNull(elements.codecClass());
+ assertEquals(elements.arrayComponent().codecClass(), ACodec.class);
+ }
+
+ @Test
+ public void testOwnerSubstitution() throws Exception {
+ if (JdkVersion.MAJOR_VERSION <= 11) {
+ throw new SkipException(
+ "JDK 11 and earlier do not expose member-class generic field type-use metadata");
+ }
+ JsonTypeUse owner = typeUse("envelope");
+ Field value = Envelope.class.getDeclaredField("value");
+ assertNull(JsonTypeUse.forField(value));
+
+ JsonTypeUse resolved =
+ JsonTypeUse.resolveMember(
+ TypeRef.of(owner.type()), owner, value.getGenericType(), null, "Envelope.value");
+ assertEquals(resolved.rawType(), String.class);
+ assertEquals(resolved.codecClass(), ACodec.class);
+ }
+
+ @Test
+ public void testHierarchyProjection() throws Exception {
+ if (JdkVersion.MAJOR_VERSION <= 11) {
+ throw new SkipException(
+ "JDK 11 and earlier do not expose member-class generic field type-use metadata");
+ }
+ JsonTypeUse values = typeUse("reorderedValues");
+ JsonTypeUse collection = values.projectTo(Collection.class, "reorderedValues");
+ assertEquals(collection.argumentCount(), 1);
+ assertEquals(collection.argument(0).rawType(), Integer.class);
+ assertEquals(collection.argument(0).codecClass(), ACodec.class);
+
+ JsonTypeUse entries = typeUse("reorderedEntries");
+ JsonTypeUse map = entries.projectTo(Map.class, "reorderedEntries");
+ assertEquals(map.argument(0).rawType(), String.class);
+ assertFalse(map.argument(0).hasExplicitCodec());
+ assertEquals(map.argument(1).rawType(), Integer.class);
+ assertEquals(map.argument(1).codecClass(), ACodec.class);
+ }
+
+ @Test
+ public void testMergeAndWildcardRejection() throws Exception {
+ JsonTypeUse first = typeUse("values");
+ JsonTypeUse same = typeUse("sameValues");
+ assertEquals(JsonTypeUse.merge(first, same, "value"), first);
+
+ JsonTypeUse conflicting = typeUse("conflictingValues");
+ assertThrows(ForyJsonException.class, () -> JsonTypeUse.merge(first, conflicting, "value"));
+ assertThrows(ForyJsonException.class, () -> typeUse("wildcard"));
+ }
+
+ private static JsonTypeUse typeUse(String name) throws Exception {
+ return JsonTypeUse.forField(Models.class.getDeclaredField(name));
+ }
+
+ private static final class Models {
+ List<@JsonCodec(ACodec.class) String> values;
+ List<@JsonCodec(ACodec.class) String> sameValues;
+ List<@JsonCodec(BCodec.class) String> conflictingValues;
+ String @JsonCodec(ACodec.class) [] array;
+
+ @JsonCodec(ACodec.class)
+ String[] elements;
+
+ Envelope<@JsonCodec(ACodec.class) String> envelope;
+ ReorderedValues<String, @JsonCodec(ACodec.class) Integer> reorderedValues;
+ ReorderedEntries<@JsonCodec(ACodec.class) Integer, String> reorderedEntries;
+ List<@JsonCodec(ACodec.class) ? extends String> wildcard;
+ }
+
+ private static final class Envelope<T> {
+ T value;
+ }
+
+ private static final class ReorderedValues<K, V> extends ArrayList<V> {}
+
+ private static final class ReorderedEntries<V, K> extends HashMap<K, V> {}
+
+ public static final class ACodec extends NullCodec {}
+
+ public static final class BCodec extends NullCodec {}
+
+ public abstract static class NullCodec implements JsonValueCodec<Object> {
+ @Override
+ public void writeString(StringJsonWriter writer, Object value) {
+ writer.writeNull();
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, Object value) {
+ writer.writeNull();
+ }
+
+ @Override
+ public Object readLatin1(Latin1JsonReader reader) {
+ reader.skipValue();
+ return null;
+ }
+
+ @Override
+ public Object readUtf16(Utf16JsonReader reader) {
+ reader.skipValue();
+ return null;
+ }
+
+ @Override
+ public Object readUtf8(Utf8JsonReader reader) {
+ reader.skipValue();
+ return null;
+ }
+ }
+}
diff --git a/java/fory-json/src/test/java/org/apache/fory/json/writer/Jdk25MultiReleaseJarVerifier.java b/java/fory-json/src/test/java/org/apache/fory/json/writer/Jdk25MultiReleaseJarVerifier.java
index 24d4be303..b6755ae4d 100644
--- a/java/fory-json/src/test/java/org/apache/fory/json/writer/Jdk25MultiReleaseJarVerifier.java
+++ b/java/fory-json/src/test/java/org/apache/fory/json/writer/Jdk25MultiReleaseJarVerifier.java
@@ -161,6 +161,8 @@ public final class Jdk25MultiReleaseJarVerifier {
compile.add(classes.toString());
compile.add(sourceRoot.resolve("module-info.java").toString());
compile.add(sourceRoot.resolve("probe/Probe.java").toString());
+ compile.add(sourceRoot.resolve("opened/OpenedValue.java").toString());
+ compile.add(sourceRoot.resolve("closed/ClosedValue.java").toString());
Process compiler = new ProcessBuilder(compile).inheritIO().start();
require(compiler.waitFor() == 0, "named-module custom codec compilation failed");
diff --git a/java/fory-json/src/test/resources/module-codec-probe/closed/ClosedValue.java b/java/fory-json/src/test/resources/module-codec-probe/closed/ClosedValue.java
new file mode 100644
index 000000000..193e338c0
--- /dev/null
+++ b/java/fory-json/src/test/resources/module-codec-probe/closed/ClosedValue.java
@@ -0,0 +1,70 @@
+/*
+ * 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 closed;
+
+import org.apache.fory.json.annotation.JsonCodec;
+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;
+
+@JsonCodec(ClosedValue.Codec.class)
+public final class ClosedValue {
+ public final String text;
+
+ public ClosedValue(String text) {
+ this.text = text;
+ }
+
+ public static final class Codec implements JsonValueCodec<ClosedValue> {
+ public static int constructions;
+
+ public Codec() {
+ constructions++;
+ }
+
+ @Override
+ public void writeString(StringJsonWriter writer, ClosedValue value) {
+ writer.writeString(value.text);
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, ClosedValue value) {
+ writer.writeString(value.text);
+ }
+
+ @Override
+ public ClosedValue readLatin1(Latin1JsonReader reader) {
+ return new ClosedValue(reader.readString());
+ }
+
+ @Override
+ public ClosedValue readUtf16(Utf16JsonReader reader) {
+ return new ClosedValue(reader.readString());
+ }
+
+ @Override
+ public ClosedValue readUtf8(Utf8JsonReader reader) {
+ return new ClosedValue(reader.readString());
+ }
+ }
+}
diff --git a/java/fory-json/src/test/resources/module-codec-probe/module-info.java b/java/fory-json/src/test/resources/module-codec-probe/module-info.java
index 5732012da..cd66916bf 100644
--- a/java/fory-json/src/test/resources/module-codec-probe/module-info.java
+++ b/java/fory-json/src/test/resources/module-codec-probe/module-info.java
@@ -21,4 +21,5 @@ module fory.json.codec.probe {
requires org.apache.fory.json;
exports probe;
+ opens opened to org.apache.fory.json;
}
diff --git a/java/fory-json/src/test/resources/module-codec-probe/opened/OpenedValue.java b/java/fory-json/src/test/resources/module-codec-probe/opened/OpenedValue.java
new file mode 100644
index 000000000..14403c60c
--- /dev/null
+++ b/java/fory-json/src/test/resources/module-codec-probe/opened/OpenedValue.java
@@ -0,0 +1,64 @@
+/*
+ * 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 opened;
+
+import org.apache.fory.json.annotation.JsonCodec;
+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;
+
+@JsonCodec(OpenedValue.Codec.class)
+public final class OpenedValue {
+ public final String text;
+
+ public OpenedValue(String text) {
+ this.text = text;
+ }
+
+ public static final class Codec implements JsonValueCodec<OpenedValue> {
+ @Override
+ public void writeString(StringJsonWriter writer, OpenedValue value) {
+ writer.writeString(value.text);
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, OpenedValue value) {
+ writer.writeString(value.text);
+ }
+
+ @Override
+ public OpenedValue readLatin1(Latin1JsonReader reader) {
+ return new OpenedValue(reader.readString());
+ }
+
+ @Override
+ public OpenedValue readUtf16(Utf16JsonReader reader) {
+ return new OpenedValue(reader.readString());
+ }
+
+ @Override
+ public OpenedValue readUtf8(Utf8JsonReader reader) {
+ return new OpenedValue(reader.readString());
+ }
+ }
+}
diff --git a/java/fory-json/src/test/resources/module-codec-probe/probe/Probe.java b/java/fory-json/src/test/resources/module-codec-probe/probe/Probe.java
index 88248ca2d..720a8e71d 100644
--- a/java/fory-json/src/test/resources/module-codec-probe/probe/Probe.java
+++ b/java/fory-json/src/test/resources/module-codec-probe/probe/Probe.java
@@ -19,11 +19,15 @@
package probe;
+import closed.ClosedValue;
import java.nio.charset.StandardCharsets;
+import opened.OpenedValue;
import org.apache.fory.json.ForyJson;
+import org.apache.fory.json.ForyJsonException;
import org.apache.fory.json.PropertyNamingStrategy;
+import org.apache.fory.json.annotation.JsonCodec;
import org.apache.fory.json.annotation.JsonProperty;
-import org.apache.fory.json.codec.JsonCodec;
+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;
@@ -50,6 +54,40 @@ public final class Probe {
"\"utf8\"".getBytes(StandardCharsets.UTF_8), Value.class)
.text));
+ ForyJson annotated = ForyJson.builder().withAsyncCompilation(false).build();
+ AnnotatedHolder holder = new AnnotatedHolder();
+ holder.value = new AnnotatedValue("annotated");
+ require("{\"value\":\"annotated\"}".equals(annotated.toJson(holder)));
+ require(
+ "{\"value\":\"annotated\"}"
+ .equals(new String(annotated.toJsonBytes(holder), StandardCharsets.UTF_8)));
+ require(
+ "latin"
+ .equals(
+ annotated.fromJson("{\"value\":\"latin\"}", AnnotatedHolder.class).value.text));
+ require(
+ "\u6587"
+ .equals(
+ annotated.fromJson("{\"value\":\"\u6587\"}", AnnotatedHolder.class).value.text));
+ require(
+ "utf8"
+ .equals(
+ annotated
+ .fromJson(
+ "{\"value\":\"utf8\"}".getBytes(StandardCharsets.UTF_8),
+ AnnotatedHolder.class)
+ .value
+ .text));
+ require("\"opened\"".equals(annotated.toJson(new OpenedValue("opened"))));
+ require("opened".equals(annotated.fromJson("\"opened\"", OpenedValue.class).text));
+ try {
+ annotated.toJson(new ClosedValue("closed"));
+ throw new AssertionError("closed codec package must be rejected");
+ } catch (ForyJsonException expected) {
+ require(expected.getMessage().contains("export or open package closed"));
+ require(ClosedValue.Codec.constructions == 0);
+ }
+
ForyJson generated =
ForyJson.builder()
.withAsyncCompilation(false)
@@ -90,7 +128,57 @@ public final class Probe {
public Pojo() {}
}
- private static final class Codec implements JsonCodec<Value> {
+ @JsonCodec(AnnotatedCodec.class)
+ public static final class AnnotatedValue {
+ private final String text;
+
+ private AnnotatedValue(String text) {
+ this.text = text;
+ }
+ }
+
+ public static final class AnnotatedHolder {
+ public AnnotatedValue value;
+
+ public AnnotatedHolder() {}
+ }
+
+ public static final class AnnotatedCodec implements JsonValueCodec<AnnotatedValue> {
+ @Override
+ public void writeString(StringJsonWriter writer, AnnotatedValue value) {
+ if (value == null) {
+ writer.writeNull();
+ } else {
+ writer.writeString(value.text);
+ }
+ }
+
+ @Override
+ public void writeUtf8(Utf8JsonWriter writer, AnnotatedValue value) {
+ if (value == null) {
+ writer.writeNull();
+ } else {
+ writer.writeString(value.text);
+ }
+ }
+
+ @Override
+ public AnnotatedValue readLatin1(Latin1JsonReader reader) {
+ return reader.tryReadNullToken() ? null : new AnnotatedValue(reader.readString());
+ }
+
+ @Override
+ public AnnotatedValue readUtf16(Utf16JsonReader reader) {
+ return reader.tryReadNullToken() ? null : new AnnotatedValue(reader.readString());
+ }
+
+ @Override
+ public AnnotatedValue readUtf8(Utf8JsonReader reader) {
+ return reader.tryReadNullToken() ? null : new AnnotatedValue(reader.readString());
+ }
+ }
+
+ private static final class Codec implements JsonValueCodec<Value> {
@Override
public void writeString(StringJsonWriter writer, Value value) {
require(writer.typeResolver() != null);
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@fory.apache.org
For additional commands, e-mail: commits-help@fory.apache.org