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/10/04 09:15:37 UTC

(fory) branch main updated: perf(java): skip runtime NON_EMPTY checks for final JSON property types (#4111)

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 e6748688e perf(java): skip runtime NON_EMPTY checks for final JSON property types (#4111)
e6748688e is described below

commit e6748688e9ad805ba3685c0852249b22877aa7c7
Author: Pavel Ptashyts <49...@users.noreply.github.com>
AuthorDate: Sun Oct 4 11:15:33 2026 +0200

    perf(java): skip runtime NON_EMPTY checks for final JSON property types (#4111)
    
    ## Why?
    
    Since #4074 the generated JSON writer calls
    `JsonFieldInfo.isEmpty(value, wpN.writeTypeInfo(), writer)` for every
    omit-empty property whose declared type is not a `CharSequence`, array,
    `Collection`, `Map` or `Optional*`. For boxed numbers, `Boolean`, enums
    and other final types that call can only ever return `false`, yet every
    write pays the `instanceof` chain in `JsonFieldInfo.isEmpty` plus an
    interface call to the codec. With `NON_EMPTY` as the default inclusion
    this makes writes of number-heavy beans about 2.2 times slower than in
    1.7.3 (details and a reproducer in #4105).
    
    ## What does this PR do?
    
    - `JsonWriterCodegen.neverEmpty` decides the emptiness check while the
    writer is generated: when `JsonFieldInfo.mayBeEmpty()` rules out every
    built-in empty type (a final or enum declared type) and neither the
    property's write codec class nor any of its superclasses or
    superinterfaces declares `isEmpty` (only the `JsonValueCodec` default
    applies), the generated String and UTF-8 writers emit only the null
    check, and `fieldWriteSize` no longer counts a check that is not
    emitted.
    - Everything else keeps the runtime call: non-final declared types,
    whose runtime value may still be a string, collection or map (this
    includes `BigDecimal` and `BigInteger`, which are not final), and codecs
    that override `isEmpty`, whether they come from `registerCodec`, a codec
    factory, `@JsonCodec` or a Mixin.
    - The decision stays in code generation on purpose. Native images
    resolve types at run time without reflection metadata for codec methods,
    so the reflective `isEmpty` lookup must not run in
    `JsonFieldInfo.resolveTypes`.
    - Generated writer classes are shared across `ForyJson` instances. The
    decision depends only on the declared type, fixed by the owner class,
    and on the write codec class, which the generated class key already
    carries (`EXACT_CODEC`, `FACTORY`, `MIXIN`);
    `GeneratedCodecKeyBuilder.addRegistration` now notes that dependency.
    The `mayBeEmpty` and `isEmpty` javadocs point at each other, since the
    built-in empty types must stay in sync.
    - Tests in `JsonGeneratedCodecTest`:
    - `nonEmptyFinalValues` inspects the generated String and UTF-8 writer
    sources (no runtime check for `Integer`, `Long`, a plain enum, an enum
    with constant bodies and a final bean; the check kept for a final type
    with an `isEmpty`-overriding `@JsonCodec`, for `BigDecimal` and for
    `Object`), checks the written JSON, and compares every fixture,
    including a 31-property bean that moves the generated group boundaries,
    with the interpreted writer. The wide bean's source is checked too, and
    it is split into member helpers, so the grouped writer shape is covered.
    It fails without the codegen change.
    - `nonEmptyRegisteredCodec` builds two instances in one JVM, one with a
    default-emptiness codec and one with an `isEmpty`-overriding codec for
    the same final type, through `registerCodec`, a codec factory, a Mixin,
    a codec inheriting `isEmpty` from an interface and one inheriting it
    from an abstract base class. It checks that both instances run different
    generated UTF-8 writers, that only the overriding one keeps the runtime
    check, and that it still omits the empty value after the other one
    generated its writer. It fails if the codec override, or the interface
    or superclass part of the walk, is ignored.
    - `builtInEmptyTypes` asserts `mayBeEmpty()` for every type
    `JsonFieldInfo.isEmpty` tests itself, including an enum implementing
    `CharSequence`, so the two lists cannot drift.
    
    ## Related issues
    
    - Fixes #4105
    
    ## AI Contribution Checklist
    
    - [x] Substantial AI assistance was used in this PR: `yes`
    - [x] 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`.
    - [x] 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.
    
    Completed checklist from `AI_POLICY.md` section 9:
    
    - [x] Substantial AI assistance was used in this PR: `yes`
    - [x] I included the standardized `AI Usage Disclosure` block below.
    - [x] I can explain and defend all important changes without AI help.
    - [x] I reviewed AI-assisted code changes line by line before
    submission.
    - [x] I completed line-by-line self-review first and fixed issues before
    requesting AI review.
    - [x] I ran two fresh AI review agents on the current PR diff or current
    HEAD after the latest code changes: one Fory-guided reviewer using
    `AGENTS.md` and `.agents/ci-and-pr.md`, and one independent general
    reviewer in a separate clean-context review session that was not pointed
    to `.agents/ci-and-pr.md` or any copied Fory-specific review checklist.
    - [x] I addressed all AI review comments and repeated the review loop
    until both ai reviewers reported no further actionable comments.
    - [x] I attached equivalent persisted links of the final clean AI review
    results from both fresh reviewers on the current PR head in this PR
    body.
    - [x] I ran adequate human verification and recorded evidence (checks
    run locally, pass/fail summary, and confirmation I reviewed results).
    - [x] I added/updated tests and specs where required.
    - [x] I validated protocol/performance impacts with evidence when
    applicable.
    - [x] I verified licensing and provenance compliance.
    
    ```text
    AI Usage Disclosure
    - substantial_ai_assistance: yes
    - scope: investigation, code drafting, tests, benchmark harness, PR text
    - affected_files_or_subsystems: java/fory-json codegen (JsonWriterCodegen) and its generated-codec test
    - ai_review: line-by-line self-review of the AI-drafted change is pending by the contributor (see unchecked items above). Two-reviewer loop on fresh sessions for every round, thirteen rounds. Fixed from review: reuse of JsonFieldInfo.mayBeEmpty instead of a second type list; no `&& true` / `if (true)` in generated code; group size estimate aligned with the emitted code; the decision kept in code generation after the Fory-guided reviewer found that moving it into resolveTypes breaks na [...]
    - ai_review_artifacts: Fory-guided reviewer: https://github.com/apache/fory/pull/4111#issuecomment-5926057531 ; independent general reviewer: https://github.com/apache/fory/pull/4111#issuecomment-5926057955 (both on commit 48dd8d80ee5624dc0341a71eff4dbc75ebefd9fd, final round, no further actionable comments; the current head 384b3824 is the same patch rebased onto main 7919241b with no conflicts, `git range-diff` reports it identical; earlier artifact comments refer to superseded commits)
    - human_verification: see "Verification" below
    - performance_verification: see "Benchmark" below
    - provenance_license_confirmation: all code written for this PR against the Apache Fory sources; no third-party code introduced
    ```
    
    ## Verification
    
    JDK 25.0.2, Windows 11 x86_64, from `java/`:
    
    - `mvn -pl fory-json -am install -DskipTests`: success
    - `mvn -pl fory-json test`: 1272 tests, 0 failures, 0 errors, 0 skipped
    - `mvn -pl fory-json test
    -Dtest='JsonGeneratedCodecTest#nonEmptyFinalValues'` with the
    `JsonWriterCodegen` change reverted: fails, as intended
    - `JsonGeneratedCodecTest#nonEmptyRegisteredCodec` with the
    codec-override check disabled: fails, as intended
    - `JsonGeneratedCodecTest#builtInEmptyTypes` with `OptionalInt` removed
    from `mayBeEmpty`, or with an early enum return in `mayBeEmpty`: fails,
    as intended
    - `JsonGeneratedCodecTest#nonEmptyRegisteredCodec` with the interface or
    the superclass part of the override walk removed: fails, as intended
    - `mvn -pl fory-json spotless:check checkstyle:check`: success, 0
    Checkstyle violations
    
    ## Does this PR introduce any user-facing change?
    
    - [x] Does this PR introduce any public API change? No.
    - [x] Does this PR introduce any binary protocol compatibility change?
    No. The JSON output is unchanged; only whether the writer asks the codec
    at runtime changes.
    
    ## Benchmark
    
    Standalone harness from #4105 (not JMH): a bean with 10 `String`, 20
    `Integer`, 10 `Long`, 2 `Double`, 2 `Boolean`, 3 enum, 2 `BigDecimal`
    properties and one `List<String>`, all non-null, serialized with
    `ForyJson.toJsonBytes` after a 20 s warm-up; median of 5 rounds of
    2,000,000 writes; one JVM per configuration, run one after another on an
    otherwise idle host; JDK 25.0.2, `-Xms1g -Xmx1g`. ns per write, two
    repetitions:
    
    | Build | `NON_EMPTY` | `NON_NULL` |
    | --- | ---: | ---: |
    | main 341f732b | 761 / 753 | 339 / 331 |
    | this PR | 349 / 341 | 330 / 349 |
    
    The JSON written is identical between the two builds in both modes
    (compared by digest of the output JSON line). The two `BigDecimal`
    properties still take the runtime check; the remaining `NON_EMPTY` cost
    over `NON_NULL` is within noise here.
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Co-authored-by: Claude Opus 5.5 <no...@anthropic.com>
---
 .../fory/json/codegen/JsonWriterCodegen.java       |  50 ++-
 .../org/apache/fory/json/meta/JsonFieldInfo.java   |  11 +-
 .../json/resolver/GeneratedCodecKeyBuilder.java    |   2 +
 .../apache/fory/json/JsonGeneratedCodecTest.java   | 367 +++++++++++++++++++++
 4 files changed, 425 insertions(+), 5 deletions(-)

diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonWriterCodegen.java b/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonWriterCodegen.java
index 2b260461f..a7665d14a 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonWriterCodegen.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonWriterCodegen.java
@@ -49,12 +49,14 @@ import org.apache.fory.json.codec.DirectUnboxedValueCodec;
 import org.apache.fory.json.codec.JsonUnwrappedInfo;
 import org.apache.fory.json.codec.JsonUnwrappedInfo.Group;
 import org.apache.fory.json.codec.JsonUnwrappedInfo.WriteEntry;
+import org.apache.fory.json.codec.JsonValueCodec;
 import org.apache.fory.json.codec.ObjectCodec;
 import org.apache.fory.json.codec.ObjectCodec.AnyInfo;
 import org.apache.fory.json.meta.JsonFieldInfo;
 import org.apache.fory.json.meta.JsonFieldKind;
 import org.apache.fory.json.resolver.JsonTypeInfo;
 import org.apache.fory.json.resolver.JsonTypeResolver;
+import org.apache.fory.json.writer.JsonWriter;
 import org.apache.fory.reflect.TypeRef;
 
 /**
@@ -1440,7 +1442,7 @@ abstract class JsonWriterCodegen {
           size += 16;
       }
     }
-    if (property.omitEmpty() || property.omitDefault()) {
+    if ((property.omitEmpty() && !neverEmpty(property)) || property.omitDefault()) {
       size += 12;
     }
     return size;
@@ -1511,7 +1513,10 @@ abstract class JsonWriterCodegen {
               : new Expression.ListExpression(
                   writeFieldName(property, id, commaKnown, index, writer),
                   writeValue(property, id, value, true, index, writer));
-      Expression present = new Expression.If(nonEmptyValue(property, id, value, writer), write);
+      Expression present =
+          neverEmpty(property)
+              ? write
+              : new Expression.If(nonEmptyValue(property, id, value, writer), write);
       if (property.writeNull()) {
         return new Expression.ListExpression(
             value,
@@ -1697,7 +1702,7 @@ abstract class JsonWriterCodegen {
   private static Expression presentValue(
       JsonFieldInfo property, int id, Expression value, Expression writer) {
     Expression present = ne(value, new Expression.Null(value.type(), false));
-    return property.omitEmpty()
+    return property.omitEmpty() && !neverEmpty(property)
         ? and(present, nonEmptyValue(property, id, value, writer))
         : present;
   }
@@ -1740,6 +1745,45 @@ abstract class JsonWriterCodegen {
             .inline());
   }
 
+  /**
+   * Decides the runtime {@link JsonFieldInfo#isEmpty} answer while generating. When {@link
+   * JsonFieldInfo#mayBeEmpty} rules out every built-in empty type, the answer comes only from the
+   * property's write codec; when that codec keeps the default {@link JsonValueCodec#isEmpty}, the
+   * value is never empty and the null check is enough. Generated classes are shared across
+   * instances, so the codec must be fixed by the generated class key: a registered codec's class, a
+   * codec factory key and a Mixin are key parts, and an annotation-selected codec is fixed by the
+   * owner class. Only code generation calls this: native images resolve types at run time without
+   * reflection metadata for codec methods.
+   */
+  private static boolean neverEmpty(JsonFieldInfo property) {
+    return !property.mayBeEmpty()
+        && !declaresIsEmpty(property.writeTypeInfo().valueCodec().getClass());
+  }
+
+  // Walks classes and interfaces explicitly: Class.getMethod may pick either of two equally
+  // specific interface declarations, and an override inherited from an interface must count.
+  private static boolean declaresIsEmpty(Class<?> type) {
+    if (type == null || type == JsonValueCodec.class) {
+      return false;
+    }
+    for (Method method : type.getDeclaredMethods()) {
+      if (method.getName().equals("isEmpty")
+          && method.getParameterCount() == 2
+          && method.getParameterTypes()[0] == JsonWriter.class) {
+        return true;
+      }
+    }
+    if (declaresIsEmpty(type.getSuperclass())) {
+      return true;
+    }
+    for (Class<?> superInterface : type.getInterfaces()) {
+      if (declaresIsEmpty(superInterface)) {
+        return true;
+      }
+    }
+    return false;
+  }
+
   private Expression writeUnboxed(
       JsonGeneratedCodecBuilder builder,
       JsonFieldInfo property,
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 fb78b90eb..e08cbd657 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
@@ -628,7 +628,11 @@ public final class JsonFieldInfo {
 
   /**
    * Returns whether the logical write type can contain an empty value, independently of its
-   * carrier.
+   * carrier. This covers only the built-in empty types that {@link #isEmpty} tests before it
+   * delegates to the codec, so a false answer does not mean the value is never empty: a codec that
+   * overrides {@link JsonValueCodec#isEmpty} still decides. Generated writers combine both, so this
+   * must list every built-in empty type {@link #isEmpty} tests; object codec validation of required
+   * NON_EMPTY properties uses this type check alone.
    */
   public boolean mayBeEmpty() {
     Class<?> type = writeTypeRef == null ? null : writeTypeRef.getRawType();
@@ -641,12 +645,15 @@ public final class JsonFieldInfo {
             || type == OptionalInt.class
             || type == OptionalLong.class
             || type == OptionalDouble.class
+            // An enum constant body cannot add interfaces, so an enum value is never one of the
+            // built-in empty types above unless its declared enum is.
             || !Modifier.isFinal(type.getModifiers()) && !type.isEnum());
   }
 
   /**
    * Tests built-in empty values directly, then delegates to the selected codec. Null omission is
-   * handled separately by the containing field's nullability contract.
+   * handled separately by the containing field's nullability contract. A new built-in empty type
+   * here must also be added to {@link #mayBeEmpty}.
    */
   @Internal
   public static boolean isEmpty(Object value, JsonTypeInfo typeInfo, JsonWriter writer) {
diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/GeneratedCodecKeyBuilder.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/GeneratedCodecKeyBuilder.java
index 1438f730c..004c8b6fe 100644
--- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/GeneratedCodecKeyBuilder.java
+++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/GeneratedCodecKeyBuilder.java
@@ -209,6 +209,8 @@ final class GeneratedCodecKeyBuilder {
     }
   }
 
+  // Generated writers decide NON_EMPTY checks from the property codec class (see
+  // JsonWriterCodegen.neverEmpty), so a registered or factory-created codec must stay a key part.
   private void addRegistration(JsonTypeInfo typeInfo) {
     // Self calls and stored child capabilities have different generated constructor shapes.
     // Subtype occurrences can have distinct owners even when their raw classes are identical.
diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonGeneratedCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonGeneratedCodecTest.java
index a7c3f7392..880a7fe1b 100644
--- a/java/fory-json/src/test/java/org/apache/fory/json/JsonGeneratedCodecTest.java
+++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonGeneratedCodecTest.java
@@ -31,32 +31,47 @@ import static org.testng.Assert.assertTrue;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
+import java.math.BigDecimal;
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.HashMap;
 import java.util.LinkedHashSet;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalDouble;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
 import java.util.Set;
 import org.apache.fory.codegen.CodeGenerator;
 import org.apache.fory.codegen.CompileUnit;
 import org.apache.fory.codegen.JaninoUtils;
+import org.apache.fory.json.annotation.JsonCodec;
+import org.apache.fory.json.annotation.JsonMixin;
+import org.apache.fory.json.annotation.JsonProperty.Include;
+import org.apache.fory.json.codec.AbstractJsonValueCodec;
+import org.apache.fory.json.codec.JsonValueCodec;
 import org.apache.fory.json.codec.ObjectCodec;
 import org.apache.fory.json.codec.Utf8WriterCodec;
 import org.apache.fory.json.codegen.JsonCodegen;
 import org.apache.fory.json.data.GeneratedCollectionFields;
+import org.apache.fory.json.data.Kind;
 import org.apache.fory.json.data.PublicFields;
 import org.apache.fory.json.data.RecursiveChild;
 import org.apache.fory.json.data.RecursiveParent;
 import org.apache.fory.json.data.TokenGroup;
 import org.apache.fory.json.data.TokenValues;
 import org.apache.fory.json.meta.JsonAsciiToken;
+import org.apache.fory.json.meta.JsonFieldInfo;
 import org.apache.fory.json.meta.JsonFieldNameHash;
+import org.apache.fory.json.reader.JsonReader;
 import org.apache.fory.json.reader.Latin1JsonReader;
 import org.apache.fory.json.reader.Utf8JsonReader;
 import org.apache.fory.json.resolver.JsonTypeInfo;
 import org.apache.fory.json.resolver.JsonTypeResolver;
+import org.apache.fory.json.writer.JsonWriter;
 import org.apache.fory.reflect.TypeRef;
 import org.apache.fory.util.ClassLoaderUtils.ByteArrayClassLoader;
 import org.testng.annotations.DataProvider;
@@ -532,6 +547,174 @@ public class JsonGeneratedCodecTest extends ForyJsonTestModels {
     }
   }
 
+  @Test
+  public void nonEmptyFinalValues() throws Exception {
+    ForyJson json = newJsonBuilder(true).defaultPropertyInclusion(Include.NON_EMPTY).build();
+    for (String role : new String[] {"StringWriter", "Utf8Writer"}) {
+      String finalValues = writerSource(json, FinalNonEmptyValues.class, role);
+      for (String field :
+          new String[] {".count;", ".total;", ".kind;", ".operation;", ".nested;"}) {
+        assertTrue(finalValues.contains(field), field + " in " + finalValues);
+      }
+      assertFalse(finalValues.contains("JsonFieldInfo.isEmpty("), finalValues);
+      // The wide bean is split into member helpers, so this covers the grouped writer shape.
+      String wideValues = writerSource(json, WideNonEmptyValues.class, role);
+      assertTrue(wideValues.contains("Members("), wideValues);
+      assertFalse(wideValues.contains("JsonFieldInfo.isEmpty("), wideValues);
+      for (Class<?> type :
+          new Class<?>[] {
+            CustomNonEmptyValue.class, DecimalNonEmptyValue.class, DynamicNonEmptyValue.class
+          }) {
+        String source = writerSource(json, type, role);
+        assertTrue(source.contains("JsonFieldInfo.isEmpty("), source);
+      }
+    }
+
+    FinalNonEmptyValues value = new FinalNonEmptyValues();
+    String expected =
+        "{\"count\":0,\"kind\":\"SMALL\",\"operation\":\"ADD\",\"nested\":{\"empty\":false}}";
+    assertJson(json, value, expected);
+    assertJson(json, new CustomNonEmptyValue(), "{}");
+    assertJson(json, new DecimalNonEmptyValue(), "{\"price\":1}");
+    assertJson(json, new DynamicNonEmptyValue(), "{}");
+    assertGeneratedWhenSupported(json, FinalNonEmptyValues.class, true);
+    assertGeneratedWhenSupported(json, CustomNonEmptyValue.class, true);
+    assertGeneratedWhenSupported(json, DecimalNonEmptyValue.class, true);
+    assertGeneratedWhenSupported(json, DynamicNonEmptyValue.class, true);
+
+    ForyJson interpreted =
+        newJsonBuilder(false).defaultPropertyInclusion(Include.NON_EMPTY).build();
+    for (Object fixture :
+        new Object[] {
+          value,
+          new CustomNonEmptyValue(),
+          new DecimalNonEmptyValue(),
+          new DynamicNonEmptyValue(),
+          new WideNonEmptyValues()
+        }) {
+      assertJson(json, fixture, interpreted.toJson(fixture));
+      assertGeneratedWhenSupported(json, fixture.getClass(), true);
+    }
+  }
+
+  @Test
+  public void builtInEmptyTypes() {
+    // Generated writers drop the emptiness check when mayBeEmpty is false, so every type that
+    // JsonFieldInfo.isEmpty tests itself must keep mayBeEmpty true.
+    JsonTypeResolver resolver = JsonTestSupport.currentTypeResolver(newJson(false));
+    for (JsonFieldInfo field : resolver.getObjectCodec(BuiltInEmptyValues.class).writeFields()) {
+      assertTrue(field.mayBeEmpty(), field.name());
+    }
+    for (JsonFieldInfo field : resolver.getObjectCodec(FinalNonEmptyValues.class).writeFields()) {
+      assertFalse(field.mayBeEmpty(), field.name());
+    }
+  }
+
+  @Test
+  public void nonEmptyRegisteredCodec() throws Exception {
+    // Generated writer classes are shared across instances, so an instance whose registered codec
+    // overrides isEmpty must keep the runtime check after an instance whose codec keeps the default
+    // has generated the writer. Only this order can observe a shared class.
+    assertRegisteredEmptiness(new RegisteredValue(), Registration.CODEC);
+    assertRegisteredEmptiness(new FactoryValue(), Registration.FACTORY);
+    assertRegisteredEmptiness(new MixinValue(), Registration.MIXIN);
+    assertRegisteredEmptiness(new InheritedValue(), Registration.INHERITED);
+    assertRegisteredEmptiness(new BaseClassValue(), Registration.BASE_CLASS);
+  }
+
+  private enum Registration {
+    CODEC,
+    FACTORY,
+    MIXIN,
+    INHERITED,
+    BASE_CLASS
+  }
+
+  private void assertRegisteredEmptiness(Object value, Registration registration) throws Exception {
+    ForyJsonBuilder plainBuilder = newJsonBuilder(true).defaultPropertyInclusion(Include.NON_EMPTY);
+    ForyJsonBuilder registeredBuilder =
+        newJsonBuilder(true).defaultPropertyInclusion(Include.NON_EMPTY);
+    if (registration == Registration.MIXIN) {
+      plainBuilder.registerMixin(PlainEmptyObjectMixin.class);
+      registeredBuilder.registerMixin(EmptyObjectMixin.class);
+    } else if (registration == Registration.FACTORY) {
+      plainBuilder.registerCodec(
+          JsonInclusionTest.EmptyObject.class,
+          (JsonCodecFactory) (type, resolver, runtimeType) -> new PlainEmptyObjectCodec());
+      registeredBuilder.registerCodec(
+          JsonInclusionTest.EmptyObject.class,
+          (JsonCodecFactory)
+              (type, resolver, runtimeType) -> new JsonInclusionTest.EmptyObjectCodec());
+    } else {
+      plainBuilder.registerCodec(JsonInclusionTest.EmptyObject.class, new PlainEmptyObjectCodec());
+      registeredBuilder.registerCodec(
+          JsonInclusionTest.EmptyObject.class,
+          registration == Registration.INHERITED
+              ? new InheritedEmptinessCodec()
+              : registration == Registration.BASE_CLASS
+                  ? new BaseClassEmptinessCodec()
+                  : new JsonInclusionTest.EmptyObjectCodec());
+    }
+    ForyJson plain = plainBuilder.build();
+    ForyJson registered = registeredBuilder.build();
+    assertJson(plain, value, "{\"value\":\"plain\"}");
+    assertJson(registered, value, "{}");
+    ForyJson interpreted =
+        newJsonBuilder(false)
+            .defaultPropertyInclusion(Include.NON_EMPTY)
+            .registerCodec(
+                JsonInclusionTest.EmptyObject.class, new JsonInclusionTest.EmptyObjectCodec())
+            .build();
+    assertEquals(interpreted.toJson(value), "{}");
+    // Both instances must run generated writers, or the outputs above would not involve the
+    // decision.
+    assertNotSame(
+        JsonTestSupport.generatedUtf8WriterClass(plain, value.getClass()),
+        JsonTestSupport.generatedUtf8WriterClass(registered, value.getClass()));
+    assertFalse(
+        writerSource(plain, value.getClass(), "Utf8Writer").contains("JsonFieldInfo.isEmpty("));
+    assertTrue(
+        writerSource(registered, value.getClass(), "Utf8Writer")
+            .contains("JsonFieldInfo.isEmpty("));
+  }
+
+  private static void assertJson(ForyJson json, Object value, String expected) {
+    assertEquals(json.toJson(value), expected);
+    assertEquals(new String(json.toJsonBytes(value), StandardCharsets.UTF_8), expected);
+  }
+
+  private String writerSource(ForyJson json, Class<?> type, String role) throws Exception {
+    JsonTypeResolver resolver = JsonTestSupport.currentTypeResolver(json);
+    ClassLoader loader = getClass().getClassLoader();
+    List<String> sources = new ArrayList<>();
+    CodeGenerator compiler =
+        new CodeGenerator(loader) {
+          @Override
+          public ClassLoader compileDirect(
+              CompileUnit unit, JaninoUtils.DirectInvocation... invocations) {
+            sources.add(unit.getCode());
+            return new ByteArrayClassLoader(JaninoUtils.toBytecode(loader, "", unit), loader);
+          }
+        };
+    Constructor<JsonCodegen> constructor =
+        JsonCodegen.class.getDeclaredConstructor(
+            CodeGenerator.class, ClassLoader.class, boolean.class, Class.class, String.class);
+    constructor.setAccessible(true);
+    JsonCodegen codegen = constructor.newInstance(compiler, loader, false, null, "NonEmpty");
+    Method build =
+        JsonCodegen.class.getDeclaredMethod(
+            "build" + role, ObjectCodec.class, JsonTypeResolver.class);
+    build.setAccessible(true);
+    resolver.lockJIT();
+    try {
+      build.invoke(codegen, resolver.getObjectCodec(type), resolver);
+    } finally {
+      resolver.unlockJIT();
+    }
+    assertEquals(sources.size(), 1);
+    return sources.get(0);
+  }
+
   private static void assertWideFields(WideFields value) {
     assertEquals(value.f0, 0);
     assertEquals(value.f1, "one");
@@ -669,6 +852,190 @@ public class JsonGeneratedCodecTest extends ForyJsonTestModels {
     public int id;
   }
 
+  public static final class FinalNonEmptyValues {
+    public Integer count = 0;
+    public Long total;
+    public Kind kind = Kind.SMALL;
+    public Operation operation = Operation.ADD;
+    public JsonInclusionTest.EmptyObject nested = new JsonInclusionTest.EmptyObject();
+  }
+
+  // The constant bodies make Operation non-final, so it covers the enum clause of mayBeEmpty.
+  public enum Operation {
+    ADD {
+      @Override
+      int apply(int left, int right) {
+        return left + right;
+      }
+    },
+    SUBTRACT {
+      @Override
+      int apply(int left, int right) {
+        return left - right;
+      }
+    };
+
+    abstract int apply(int left, int right);
+  }
+
+  public static final class DecimalNonEmptyValue {
+    public BigDecimal price = BigDecimal.ONE;
+  }
+
+  public static final class CustomNonEmptyValue {
+    @JsonCodec(JsonInclusionTest.EmptyObjectCodec.class)
+    public JsonInclusionTest.EmptyObject value = emptyObject();
+
+    private static JsonInclusionTest.EmptyObject emptyObject() {
+      JsonInclusionTest.EmptyObject value = new JsonInclusionTest.EmptyObject();
+      value.empty = true;
+      return value;
+    }
+  }
+
+  public static final class PlainEmptyObjectCodec
+      extends AbstractJsonValueCodec<JsonInclusionTest.EmptyObject> {
+    @Override
+    public void write(JsonWriter writer, JsonInclusionTest.EmptyObject value) {
+      writer.writeString("plain");
+    }
+
+    @Override
+    public JsonInclusionTest.EmptyObject read(JsonReader reader) {
+      reader.readString();
+      return new JsonInclusionTest.EmptyObject();
+    }
+  }
+
+  // Generated classes are cached per owner class, so each registration kind needs its own owner.
+  public static final class RegisteredValue {
+    public JsonInclusionTest.EmptyObject value = CustomNonEmptyValue.emptyObject();
+  }
+
+  public static final class FactoryValue {
+    public JsonInclusionTest.EmptyObject value = CustomNonEmptyValue.emptyObject();
+  }
+
+  public interface EmptyObjectEmptiness extends JsonValueCodec<JsonInclusionTest.EmptyObject> {
+    @Override
+    default boolean isEmpty(JsonWriter writer, JsonInclusionTest.EmptyObject value) {
+      return value.empty;
+    }
+  }
+
+  // Inherits isEmpty from an interface instead of declaring it.
+  public static final class InheritedEmptinessCodec
+      extends AbstractJsonValueCodec<JsonInclusionTest.EmptyObject>
+      implements EmptyObjectEmptiness {
+    @Override
+    public void write(JsonWriter writer, JsonInclusionTest.EmptyObject value) {
+      writer.writeString("");
+    }
+
+    @Override
+    public JsonInclusionTest.EmptyObject read(JsonReader reader) {
+      reader.readString();
+      return new JsonInclusionTest.EmptyObject();
+    }
+  }
+
+  public static final class InheritedValue {
+    public JsonInclusionTest.EmptyObject value = CustomNonEmptyValue.emptyObject();
+  }
+
+  public abstract static class EmptinessAwareCodec<T> extends AbstractJsonValueCodec<T> {
+    @Override
+    public boolean isEmpty(JsonWriter writer, T value) {
+      return ((JsonInclusionTest.EmptyObject) value).empty;
+    }
+  }
+
+  // Inherits isEmpty from an abstract base class instead of declaring it.
+  public static final class BaseClassEmptinessCodec
+      extends EmptinessAwareCodec<JsonInclusionTest.EmptyObject> {
+    @Override
+    public void write(JsonWriter writer, JsonInclusionTest.EmptyObject value) {
+      writer.writeString("");
+    }
+
+    @Override
+    public JsonInclusionTest.EmptyObject read(JsonReader reader) {
+      reader.readString();
+      return new JsonInclusionTest.EmptyObject();
+    }
+  }
+
+  public static final class BaseClassValue {
+    public JsonInclusionTest.EmptyObject value = CustomNonEmptyValue.emptyObject();
+  }
+
+  public static final class MixinValue {
+    public JsonInclusionTest.EmptyObject value = CustomNonEmptyValue.emptyObject();
+  }
+
+  @JsonMixin(target = JsonInclusionTest.EmptyObject.class)
+  @JsonCodec(PlainEmptyObjectCodec.class)
+  public interface PlainEmptyObjectMixin {}
+
+  @JsonMixin(target = JsonInclusionTest.EmptyObject.class)
+  @JsonCodec(JsonInclusionTest.EmptyObjectCodec.class)
+  public interface EmptyObjectMixin {}
+
+  public static final class WideNonEmptyValues {
+    public int id = 1;
+    public Integer v0 = 0;
+    public Long v1 = 1L;
+    public Kind v2 = Kind.FAST;
+    public Integer v3 = 3;
+    public Long v4 = 4L;
+    public Kind v5 = Kind.FAST;
+    public Integer v6 = 6;
+    public Long v7 = 7L;
+    public Kind v8 = Kind.FAST;
+    public Integer v9 = 9;
+    public Long v10 = 10L;
+    public Kind v11 = Kind.FAST;
+    public Integer v12 = 12;
+    public Long v13 = 13L;
+    public Kind v14 = Kind.FAST;
+    public Integer v15 = 15;
+    public Long v16 = 16L;
+    public Kind v17 = Kind.FAST;
+    public Integer v18 = 18;
+    public Long v19 = 19L;
+    public Kind v20 = Kind.FAST;
+    public Integer v21 = 21;
+    public Long v22 = 22L;
+    public Kind v23 = Kind.FAST;
+    public Integer v24 = 24;
+    public Long v25 = 25L;
+    public Kind v26 = Kind.FAST;
+    public Integer v27 = 27;
+    public Long v28 = 28L;
+    public Kind v29 = Kind.FAST;
+  }
+
+  public static final class BuiltInEmptyValues {
+    public String string = "";
+    public StringBuilder text = new StringBuilder();
+    public FinalList list = new FinalList();
+    public FinalMap map = new FinalMap();
+    public int[] array = new int[0];
+    public Optional<String> optional = Optional.empty();
+    public OptionalInt optionalInt = OptionalInt.empty();
+    public OptionalLong optionalLong = OptionalLong.empty();
+    public OptionalDouble optionalDouble = OptionalDouble.empty();
+    public JsonInclusionTest.TextEnum textEnum = JsonInclusionTest.TextEnum.EMPTY;
+  }
+
+  public static final class FinalList extends ArrayList<String> {}
+
+  public static final class FinalMap extends HashMap<String, String> {}
+
+  public static final class DynamicNonEmptyValue {
+    public Object value = "";
+  }
+
   private static String objectCollectionsJson(String name) {
     StringBuilder values = new StringBuilder();
     for (int i = 0; i < 10; i++) {


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@fory.apache.org
For additional commands, e-mail: commits-help@fory.apache.org