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 2bab1661c feat(java): support graalvm 25 (#2652)
2bab1661c is described below

commit 2bab1661c26cf907912fc85633847d9a828f25a3
Author: Shawn Yang <[email protected]>
AuthorDate: Wed Sep 24 16:17:16 2025 +0800

    feat(java): support graalvm 25 (#2652)
    
    ## Why?
    
    Graalvm 25 needs configure `unsafeAllocate` for object creation by
    `Unsafe`, which is not easy to use.
    
    ## What does this PR do?
    
    This PR provide a unified mechanism to create objects to support
    graalvm25
    
    ## Related issues
    
    Fixes #2647
    https://github.com/oracle/graal/issues/12220
    ## Does this PR introduce any user-facing change?
    
    <!--
    If any user-facing interface changes, please [open an
    issue](https://github.com/apache/fory/issues/new/choose) describing the
    need to do so and update the document if necessary.
    
    Delete section if not applicable.
    -->
    
    - [ ] Does this PR introduce any public API change?
    - [ ] Does this PR introduce any binary protocol compatibility change?
    
    ## Benchmark
    
    <!--
    When the PR has an impact on performance (if you don't know whether the
    PR will have an impact on performance, you can submit the PR first, and
    if it will have impact on performance, the code reviewer will explain
    it), be sure to attach a benchmark data here.
    
    Delete section if not applicable.
    -->
---
 .github/workflows/ci.yml                           |   2 +-
 .gitignore                                         |  41 +++-
 AGENTS.md                                          |  15 +-
 docs/guide/graalvm_guide.md                        |  37 ++-
 .../java/org/apache/fory/builder/CodecBuilder.java |  22 ++
 .../fory/builder/CompatibleCodecBuilder.java       |  10 +-
 .../apache/fory/builder/ObjectCodecBuilder.java    |   9 +-
 .../apache/fory/collection/ClassValueCache.java    |  11 +-
 .../org/apache/fory/logging/LoggerFactory.java     |   2 +-
 .../org/apache/fory/reflect/FieldAccessor.java     |   9 +-
 .../org/apache/fory/reflect/ObjectCreator.java     |  64 +++++
 .../org/apache/fory/reflect/ObjectCreators.java    | 265 +++++++++++++++++++++
 .../org/apache/fory/reflect/ReflectionUtils.java   |  18 +-
 .../org/apache/fory/resolver/ClassResolver.java    |   2 +
 .../fory/serializer/AbstractObjectSerializer.java  |  27 +--
 .../fory/serializer/CompatibleSerializer.java      |  17 +-
 .../fory/serializer/CompatibleSerializerBase.java  |   6 +-
 .../fory/serializer/ExternalizableSerializer.java  |  18 +-
 .../fory/serializer/MetaSharedSerializer.java      |  14 +-
 .../apache/fory/serializer/ObjectSerializer.java   |  11 +-
 .../fory/serializer/ObjectStreamSerializer.java    |  24 +-
 .../java/org/apache/fory/util/GraalvmSupport.java  |  33 +++
 .../org/apache/fory/util/record/RecordUtils.java   |   9 -
 .../fory-core/native-image.properties              |   5 +
 .../apache/fory/reflect/ObjectCreatorsTest.java}   |  38 +--
 .../apache/fory/reflect/ReflectionUtilsTest.java   |  27 +++
 26 files changed, 580 insertions(+), 156 deletions(-)

diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 45266a3e8..3bcf1a32e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -130,7 +130,7 @@ jobs:
     runs-on: ubuntu-latest
     strategy:
       matrix:
-        java-version: ["17", "21", "23"]
+        java-version: ["17", "21", "25"]
     steps:
       - uses: actions/checkout@v5
       - uses: graalvm/setup-graalvm@v1
diff --git a/.gitignore b/.gitignore
index 682625a42..6ef4161d1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -41,4 +41,43 @@ MODULE.bazel.lock
 .DS_Store
 **/.DS_Store
 .vscode/
-go/fory/.gocache
\ No newline at end of file
+go/fory/.gocache
+
+# Build directories for all languages
+# Java
+**/target/
+java/**/target/
+
+# Python
+python/build/
+python/dist/
+**/build/
+**/dist/
+
+# C++
+cpp/build/
+cpp/bazel-*
+
+# Bazel build directories
+bazel-out/
+bazel-bin/
+bazel-testlogs/
+bazel-genfiles//
+
+# Go
+go/**/build/
+
+# Rust
+rust/target/
+
+# JavaScript/Node.js
+**/node_modules/
+javascript/**/build/
+
+# General build artifacts
+build/
+dist/
+**/.ruff_cache
+**/.pytest_cache
+.venv
+**/.idea
diff --git a/AGENTS.md b/AGENTS.md
index a22fd22cc..a69285288 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -12,6 +12,7 @@ While working on Fory, please remember:
 - **Focused Testing**: Only add tests that verify internal behaviors or fix 
specific bugs; don't create unnecessary tests unless requested.
 - **Git-Tracked Files**: When reading code, skip all files not tracked by git 
by default unless generated by yourself.
 - **Cross-Language Consistency**: Maintain consistency across language 
implementations while respecting language-specific idioms.
+- **Graalvm Support using fory codegen**: For graalvm, please use `fory 
codegen` to generate the serializer when building graalvm native image, do not 
use graallvm reflect-related configuration unless for JDK `proxy`.
 
 ## Build and Development Commands
 
@@ -114,9 +115,6 @@ go test -race -v
 # Build
 go build
 
-# Run linter (if golangci-lint is installed)
-golangci-lint run
-
 # Generate code (if using go:generate)
 go generate ./...
 ```
@@ -249,6 +247,13 @@ cd $it_dir/cpython_benchmark && pip install -r 
requirements.txt && python benchm
 
 ## Repository Structure Understanding
 
+### Git Repository
+
+Apache Fory is an open-source project hosted on GitHub.
+The git repository for Apache Fory is https://github.com/apache/fory .
+Contributors always fork the repository and create a pull request to propose 
changes.
+The `origin` points to forked repository instead of the official repository.
+
 ### Key Directories
 
 - **`docs/`**: Documentation, specifications, and guides
@@ -419,7 +424,9 @@ Fory rust provides macro-based serialization and 
deserialization. Fory rust cons
 `integration_tests` contains integration tests with following modules:
 
 - **cpython_benchmark**: benchmark suite for fory python
-- **graalvm_tests**: test suite for fory java on graalvm
+- **graalvm_tests**: test suite for fory java on graalvm.
+  - Note that fory use codegen to support graalvm instead of reflection, fory 
don't use `reflect-config.json` for
+    serialization, this is the core advantage of compared to graalvm JDK 
serialization.
 - **jdk_compatibility_tests**: test suite for fory serialization compatibility 
between multiple JDK versions
 - **latest_jdk_tests**: test suite for `jdk17+` versions
 
diff --git a/docs/guide/graalvm_guide.md b/docs/guide/graalvm_guide.md
index 190614953..6c5174fd9 100644
--- a/docs/guide/graalvm_guide.md
+++ b/docs/guide/graalvm_guide.md
@@ -37,14 +37,43 @@ build time. For example, here we configure 
`org.apache.fory.graalvm.Example` cla
 Args = --initialize-at-build-time=org.apache.fory.graalvm.Example
 ```
 
-Another benefit using fory is that you don't have to configure [reflection 
json](https://www.graalvm.org/latest/reference-manual/native-image/metadata/#specifying-reflection-metadata-in-json)
 and
-[serialization 
json](https://www.graalvm.org/latest/reference-manual/native-image/metadata/#serialization),
 which is
-very tedious, cumbersome and inconvenient. When using fory, you just need to 
invoke
-`org.apache.fory.Fory.register(Class<?>, boolean)` for every type you want to 
serialize.
+**The main benefit of using Fory with GraalVM is that you don't need to 
configure [reflection 
json](https://www.graalvm.org/latest/reference-manual/native-image/metadata/#specifying-reflection-metadata-in-json)
 or
+[serialization 
json](https://www.graalvm.org/latest/reference-manual/native-image/metadata/#serialization)
 for your serializable classes!** This eliminates the tedious, cumbersome and 
error-prone configuration process.
+
+Fory achieves this by using **codegen instead of reflection** - all 
serialization code is generated at build time when you call:
+
+- `fory.register(YourClass.class, true)` to register your classes
+- `fory.ensureSerializersCompiled()` to compile serializers at build time
 
 Note that Fory `asyncCompilationEnabled` option will be disabled automatically 
for graalvm native image since graalvm
 native image doesn't support JIT at the image run time.
 
+## Registering Your Classes
+
+If you encounter a GraalVM error like:
+
+```
+Type com.example.MyClass is instantiated reflectively but was never registered
+```
+
+This means you need to register your class with Fory. **Do NOT add it to 
reflect-config.json** - instead, register it with Fory's codegen system:
+
+```java
+static {
+  fory = Fory.builder().build();
+  fory.register(MyClass.class, true);  // Enable codegen for this class
+  fory.ensureSerializersCompiled();    // Compile at build time
+}
+```
+
+And make sure the class executing static registering is initialized at build 
time in `native-image.properties`:
+
+```properties
+Args = --initialize-at-build-time=com.example.MyForySerializer
+```
+
+This approach is much more efficient than reflection-based serialization and 
eliminates the need for complex GraalVM configuration files.
+
 ## Not thread-safe Fory
 
 Example:
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/builder/CodecBuilder.java 
b/java/fory-core/src/main/java/org/apache/fory/builder/CodecBuilder.java
index 17a25ab03..4c3f2498d 100644
--- a/java/fory-core/src/main/java/org/apache/fory/builder/CodecBuilder.java
+++ b/java/fory-core/src/main/java/org/apache/fory/builder/CodecBuilder.java
@@ -56,6 +56,8 @@ import org.apache.fory.codegen.Expression.StaticInvoke;
 import org.apache.fory.collection.Tuple2;
 import org.apache.fory.memory.MemoryBuffer;
 import org.apache.fory.memory.Platform;
+import org.apache.fory.reflect.ObjectCreator;
+import org.apache.fory.reflect.ObjectCreators;
 import org.apache.fory.reflect.ReflectionUtils;
 import org.apache.fory.reflect.TypeRef;
 import org.apache.fory.resolver.ClassInfo;
@@ -178,6 +180,8 @@ public abstract class CodecBuilder {
     String fieldName = "_record_ctr_";
     Reference fieldRef = fieldMap.get(fieldName);
     if (fieldRef == null) {
+      // trigger cache for graalvm
+      RecordUtils.getRecordCtrHandle(beanClass);
       StaticInvoke getRecordCtrHandle =
           new StaticInvoke(
               RecordUtils.class,
@@ -483,10 +487,28 @@ public abstract class CodecBuilder {
     if (sourcePublicAccessible(beanClass)) {
       return new Expression.NewInstance(beanType);
     } else {
+      if (GraalvmSupport.IN_GRAALVM_NATIVE_IMAGE && Platform.JAVA_VERSION >= 
25) {
+        ObjectCreators.getObjectCreator(beanClass); // trigger cache
+        return new Invoke(getObjectCreator(beanClass), "newInstance", 
OBJECT_TYPE);
+      }
       return new StaticInvoke(Platform.class, "newInstance", OBJECT_TYPE, 
beanClassExpr());
     }
   }
 
+  protected Expression getObjectCreator(Class<?> type) {
+    ObjectCreators.getObjectCreator(type); // trigger cache
+    return getOrCreateField(
+        true,
+        ObjectCreator.class,
+        ctx.newName("objectCreator_" + type.getSimpleName()),
+        () ->
+            new StaticInvoke(
+                ObjectCreators.class,
+                "getObjectCreator",
+                TypeRef.of(ObjectCreator.class),
+                staticBeanClassExpr()));
+  }
+
   protected void buildRecordComponentDefaultValues() {
     ctx.reserveName(recordComponentDefaultValues.name());
     StaticInvoke expr =
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/builder/CompatibleCodecBuilder.java
 
b/java/fory-core/src/main/java/org/apache/fory/builder/CompatibleCodecBuilder.java
index d6b2a1254..83823b5ec 100644
--- 
a/java/fory-core/src/main/java/org/apache/fory/builder/CompatibleCodecBuilder.java
+++ 
b/java/fory-core/src/main/java/org/apache/fory/builder/CompatibleCodecBuilder.java
@@ -409,13 +409,9 @@ public class CompatibleCodecBuilder extends 
BaseObjectCodecBuilder {
             "private",
             "readFields",
             false);
-    StaticInvoke record =
-        new StaticInvoke(
-            RecordUtils.class,
-            "invokeRecordCtrHandle",
-            OBJECT_TYPE,
-            getRecordCtrHandle(),
-            components);
+    Expression record =
+        new Invoke(
+            getObjectCreator(beanClass), "newInstanceWithArguments", 
OBJECT_TYPE, components);
     return new ListExpression(buffer, components, readActions, new 
Return(record));
   }
 
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/builder/ObjectCodecBuilder.java 
b/java/fory-core/src/main/java/org/apache/fory/builder/ObjectCodecBuilder.java
index d8fca68c0..37a85e3ff 100644
--- 
a/java/fory-core/src/main/java/org/apache/fory/builder/ObjectCodecBuilder.java
+++ 
b/java/fory-core/src/main/java/org/apache/fory/builder/ObjectCodecBuilder.java
@@ -55,6 +55,7 @@ import org.apache.fory.codegen.Expression.ReplaceStub;
 import org.apache.fory.codegen.Expression.StaticInvoke;
 import org.apache.fory.codegen.ExpressionVisitor;
 import org.apache.fory.memory.Platform;
+import org.apache.fory.reflect.ObjectCreators;
 import org.apache.fory.reflect.TypeRef;
 import org.apache.fory.serializer.ObjectSerializer;
 import org.apache.fory.serializer.PrimitiveSerializers.LongSerializer;
@@ -472,13 +473,9 @@ public class ObjectCodecBuilder extends 
BaseObjectCodecBuilder {
         FieldsCollector collector = (FieldsCollector) bean;
         bean = createRecord(collector.recordValuesMap);
       } else {
+        ObjectCreators.getObjectCreator(beanClass); // trigger cache and make 
error raised early
         bean =
-            new StaticInvoke(
-                RecordUtils.class,
-                "invokeRecordCtrHandle",
-                OBJECT_TYPE,
-                getRecordCtrHandle(),
-                bean);
+            new Invoke(getObjectCreator(beanClass), 
"newInstanceWithArguments", OBJECT_TYPE, bean);
       }
     }
     expressions.add(new Expression.Return(bean));
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/collection/ClassValueCache.java 
b/java/fory-core/src/main/java/org/apache/fory/collection/ClassValueCache.java
index c9668dc34..b511fd27c 100644
--- 
a/java/fory-core/src/main/java/org/apache/fory/collection/ClassValueCache.java
+++ 
b/java/fory-core/src/main/java/org/apache/fory/collection/ClassValueCache.java
@@ -22,6 +22,7 @@ package org.apache.fory.collection;
 import com.google.common.cache.Cache;
 import com.google.common.cache.CacheBuilder;
 import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
 import org.apache.fory.annotation.Internal;
 import org.apache.fory.util.GraalvmSupport;
 
@@ -38,8 +39,12 @@ public class ClassValueCache<T> {
     return cache.getIfPresent(k);
   }
 
-  public T get(Class<?> k, Callable<? extends T> loader) throws Exception {
-    return cache.get(k, loader);
+  public T get(Class<?> k, Callable<? extends T> loader) {
+    try {
+      return cache.get(k, loader);
+    } catch (ExecutionException e) {
+      throw new RuntimeException(e);
+    }
   }
 
   public void put(Class<?> k, T v) {
@@ -75,7 +80,7 @@ public class ClassValueCache<T> {
    * @return the cache
    */
   public static <T> ClassValueCache<T> newClassKeySoftCache(int 
concurrencyLevel) {
-    if (GraalvmSupport.isGraalBuildtime()) {
+    if (GraalvmSupport.IN_GRAALVM_NATIVE_IMAGE) {
       return new ClassValueCache<>(
           
CacheBuilder.newBuilder().concurrencyLevel(concurrencyLevel).build());
     } else {
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/logging/LoggerFactory.java 
b/java/fory-core/src/main/java/org/apache/fory/logging/LoggerFactory.java
index 0466b1f74..0f50c3090 100644
--- a/java/fory-core/src/main/java/org/apache/fory/logging/LoggerFactory.java
+++ b/java/fory-core/src/main/java/org/apache/fory/logging/LoggerFactory.java
@@ -26,7 +26,7 @@ import org.apache.fory.util.GraalvmSupport;
  */
 public class LoggerFactory {
   private static volatile boolean useSlf4jLogger;
-  private static volatile int logLevel = LogLevel.ERROR_LEVEL;
+  private static volatile int logLevel = LogLevel.INFO_LEVEL;
 
   /** Disable Logger, there will be no log output. */
   public static void disableLogging() {
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/reflect/FieldAccessor.java 
b/java/fory-core/src/main/java/org/apache/fory/reflect/FieldAccessor.java
index ca2a8bafc..aa55765e1 100644
--- a/java/fory-core/src/main/java/org/apache/fory/reflect/FieldAccessor.java
+++ b/java/fory-core/src/main/java/org/apache/fory/reflect/FieldAccessor.java
@@ -506,12 +506,9 @@ public abstract class FieldAccessor {
 
     protected GeneratedAccessor(Field field) {
       super(field, -1);
-      ConcurrentMap<String, Tuple2<MethodHandle, MethodHandle>> map;
-      try {
-        map = cache.get(field.getDeclaringClass(), ConcurrentHashMap::new);
-      } catch (Exception e) {
-        throw new RuntimeException(e);
-      }
+      ConcurrentMap<String, Tuple2<MethodHandle, MethodHandle>> map =
+          cache.get(field.getDeclaringClass(), ConcurrentHashMap::new);
+      ;
       MethodHandles.Lookup lookup = 
_JDKAccess._trustedLookup(field.getDeclaringClass());
       Tuple2<MethodHandle, MethodHandle> tuple2 =
           map.computeIfAbsent(
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/reflect/ObjectCreator.java 
b/java/fory-core/src/main/java/org/apache/fory/reflect/ObjectCreator.java
new file mode 100644
index 000000000..32e58578b
--- /dev/null
+++ b/java/fory-core/src/main/java/org/apache/fory/reflect/ObjectCreator.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 org.apache.fory.reflect;
+
+/**
+ * Abstract base class for creating instances of a given type.
+ *
+ * <p>This class provides a unified interface for object instantiation across 
different creation
+ * strategies such as constructor invocation, unsafe allocation, and record 
creation.
+ * Implementations handle various scenarios including no-arg constructors, 
parameterized
+ * constructors for records, and platform-specific optimizations.
+ *
+ * <p><strong>Thread Safety:</strong> All implementations of ObjectCreator are 
thread-safe and can
+ * be safely used across multiple threads concurrently. The underlying 
creation mechanisms
+ * (MethodHandle, Constructor, Platform.newInstance) are all thread-safe.
+ *
+ * @param <T> the type of objects this creator can instantiate
+ */
+public abstract class ObjectCreator<T> {
+  protected final Class<T> type;
+
+  protected ObjectCreator(Class<T> type) {
+    this.type = type;
+  }
+
+  /**
+   * Creates a new instance of type T using the default creation strategy.
+   *
+   * @return a new instance of type T
+   * @throws RuntimeException if instance creation fails
+   * @throws UnsupportedOperationException if this creator doesn't support 
parameterless creation
+   */
+  public abstract T newInstance();
+
+  /**
+   * Creates a new instance of type T using the provided arguments.
+   *
+   * <p>This method is primarily used for record types that require 
constructor arguments. Most
+   * implementations will throw UnsupportedOperationException.
+   *
+   * @param arguments the arguments to pass to the constructor
+   * @return a new instance of type T
+   * @throws RuntimeException if instance creation fails
+   * @throws UnsupportedOperationException if this creator doesn't support 
parameterized creation
+   */
+  public abstract T newInstanceWithArguments(Object... arguments);
+}
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/reflect/ObjectCreators.java 
b/java/fory-core/src/main/java/org/apache/fory/reflect/ObjectCreators.java
new file mode 100644
index 000000000..9b61dbb98
--- /dev/null
+++ b/java/fory-core/src/main/java/org/apache/fory/reflect/ObjectCreators.java
@@ -0,0 +1,265 @@
+/*
+ * 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 java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles.Lookup;
+import java.lang.invoke.MethodType;
+import java.lang.reflect.Constructor;
+import org.apache.fory.collection.ClassValueCache;
+import org.apache.fory.collection.Tuple2;
+import org.apache.fory.exception.ForyException;
+import org.apache.fory.memory.Platform;
+import org.apache.fory.util.GraalvmSupport;
+import org.apache.fory.util.record.RecordUtils;
+import org.apache.fory.util.unsafe._JDKAccess;
+
+/**
+ * Factory class for creating and caching {@link ObjectCreator} instances.
+ *
+ * <p>This class provides a centralized way to obtain optimized object 
creators for different types.
+ * It automatically selects the most appropriate creation strategy based on 
the target type and
+ * runtime environment:
+ *
+ * <ul>
+ *   <li><strong>Record types:</strong> Uses {@link RecordObjectCreator} with 
MethodHandle for
+ *       parameterized constructor invocation
+ *   <li><strong>Classes with no-arg constructors:</strong> Uses {@link
+ *       DeclaredNoArgCtrObjectCreator} with MethodHandle for fast invocation
+ *   <li><strong>Classes without accessible constructors:</strong> Uses {@link 
UnsafeObjectCreator}
+ *       with platform-specific unsafe allocation
+ *   <li><strong>GraalVM native image compatibility:</strong> Uses {@link
+ *       ParentNoArgCtrObjectCreator} for constructor generate-based creation 
when needed
+ * </ul>
+ *
+ * <p>All created ObjectCreator instances are cached using a soft reference 
cache to improve
+ * performance on repeated requests for the same type.
+ *
+ * <p><strong>Thread Safety:</strong> This class and all returned 
ObjectCreator instances are
+ * thread-safe and can be safely used across multiple threads concurrently.
+ */
+@SuppressWarnings("unchecked")
+public class ObjectCreators {
+  private static final ClassValueCache<ObjectCreator<?>> cache =
+      ClassValueCache.newClassKeySoftCache(8);
+
+  /**
+   * Returns an optimized ObjectCreator for the given type.
+   *
+   * <p>This method automatically selects the most appropriate creation 
strategy based on the type
+   * characteristics and caches the result for future use. The selection logic 
prioritizes
+   * performance and platform compatibility.
+   *
+   * @param <T> the type for which to create an ObjectCreator
+   * @param type the Class object representing the target type
+   * @return a cached ObjectCreator instance optimized for the given type
+   * @throws ForyException if the type cannot be instantiated (e.g., missing 
no-arg constructor in
+   *     GraalVM native image)
+   */
+  public static <T> ObjectCreator<T> getObjectCreator(Class<T> type) {
+    return (ObjectCreator<T>) cache.get(type, () -> 
creategetObjectCreator(type));
+  }
+
+  private static <T> ObjectCreator<T> creategetObjectCreator(Class<T> type) {
+    if (RecordUtils.isRecord(type)) {
+      return new RecordObjectCreator<>(type);
+    }
+    Constructor<T> noArgConstructor = 
ReflectionUtils.getNoArgConstructor(type);
+    if (GraalvmSupport.IN_GRAALVM_NATIVE_IMAGE && Platform.JAVA_VERSION >= 25) 
{
+      if (noArgConstructor != null) {
+        return new DeclaredNoArgCtrObjectCreator<>(type);
+      } else {
+        return new ParentNoArgCtrObjectCreator<>(type);
+      }
+    }
+    if (noArgConstructor == null) {
+      return new UnsafeObjectCreator<>(type);
+    }
+    return new DeclaredNoArgCtrObjectCreator<>(type);
+  }
+
+  public static final class UnsafeObjectCreator<T> extends ObjectCreator<T> {
+
+    public UnsafeObjectCreator(Class<T> type) {
+      super(type);
+    }
+
+    @Override
+    public T newInstance() {
+      return Platform.newInstance(type);
+    }
+
+    @Override
+    public T newInstanceWithArguments(Object... arguments) {
+      throw new UnsupportedOperationException();
+    }
+  }
+
+  public static final class DeclaredNoArgCtrObjectCreator<T> extends 
ObjectCreator<T> {
+    private final MethodHandle handle;
+
+    public DeclaredNoArgCtrObjectCreator(Class<T> type) {
+      super(type);
+      handle = ReflectionUtils.getCtrHandle(type, true);
+    }
+
+    @Override
+    public T newInstance() {
+      try {
+        return (T) handle.invoke();
+      } catch (Throwable e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    @Override
+    public T newInstanceWithArguments(Object... arguments) {
+      throw new UnsupportedOperationException();
+    }
+  }
+
+  public static final class RecordObjectCreator<T> extends ObjectCreator<T> {
+    private final MethodHandle handle;
+    private final Constructor<?> constructor;
+
+    public RecordObjectCreator(Class<T> type) {
+      super(type);
+      Tuple2<Constructor, MethodHandle> tuple2 = 
RecordUtils.getRecordConstructor(type);
+      constructor = tuple2.f0;
+      handle = tuple2.f1;
+      if (GraalvmSupport.IN_GRAALVM_NATIVE_IMAGE && Platform.JAVA_VERSION >= 
25) {
+        try {
+          constructor.setAccessible(true);
+        } catch (Throwable t) {
+          throw new ForyException(
+              "Failed to create instance, please provide a public constructor 
for " + type, t);
+        }
+      }
+    }
+
+    @Override
+    public T newInstance() {
+      throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public T newInstanceWithArguments(Object... arguments) {
+      try {
+        // compile-time constant is eligible for dead code elimination.
+        if (GraalvmSupport.IN_GRAALVM_NATIVE_IMAGE && Platform.JAVA_VERSION >= 
25) {
+          // GraalVM 25+ path: workaround for 
https://github.com/oracle/graal/issues/12106
+          return (T) constructor.newInstance(arguments);
+        } else {
+          // Regular path: use method handle
+          return (T) handle.invokeWithArguments(arguments);
+        }
+      } catch (Throwable e) {
+        throw new RuntimeException(e);
+      }
+    }
+  }
+
+  public static final class ParentNoArgCtrObjectCreator<T> extends 
ObjectCreator<T> {
+    private static volatile Object reflectionFactory;
+    private static volatile MethodHandle newConstructorForSerializationMethod;
+
+    private final Constructor<T> constructor;
+
+    public ParentNoArgCtrObjectCreator(Class<T> type) {
+      super(type);
+      this.constructor = createSerializationConstructor(type);
+    }
+
+    private static <T> Constructor<T> createSerializationConstructor(Class<T> 
type) {
+      try {
+        // Get ReflectionFactory instance
+        if (reflectionFactory == null) {
+          Class<?> reflectionFactoryClass;
+          if (Platform.JAVA_VERSION >= 9) {
+            reflectionFactoryClass = 
Class.forName("jdk.internal.reflect.ReflectionFactory");
+          } else {
+            reflectionFactoryClass = 
Class.forName("sun.reflect.ReflectionFactory");
+          }
+          Lookup lookup = _JDKAccess._trustedLookup(reflectionFactoryClass);
+          MethodHandle handle =
+              lookup.findStatic(
+                  reflectionFactoryClass,
+                  "getReflectionFactory",
+                  MethodType.methodType(reflectionFactoryClass));
+          reflectionFactory = handle.invoke();
+          newConstructorForSerializationMethod =
+              lookup.findVirtual(
+                  reflectionFactoryClass,
+                  "newConstructorForSerialization",
+                  MethodType.methodType(Constructor.class, Class.class, 
Constructor.class));
+        }
+        // Find a public no-arg constructor in parent classes that we can use 
as a template
+        Constructor<?> parentConstructor = findPublicNoArgConstructor(type);
+        if (parentConstructor == null) {
+          // Use Object's constructor as fallback
+          parentConstructor = Object.class.getDeclaredConstructor();
+        } else {
+          try {
+            parentConstructor.newInstance();
+          } catch (Throwable ignored) {
+            parentConstructor = Object.class.getDeclaredConstructor();
+          }
+        }
+        // Create serialization constructor using ReflectionFactory
+        return (Constructor<T>)
+            newConstructorForSerializationMethod.invoke(reflectionFactory, 
type, parentConstructor);
+      } catch (Throwable e) {
+        throw new ForyException(
+            "Failed to create instance, please provide a no-arg constructor 
for " + type, e);
+      }
+    }
+
+    private static Constructor<?> findPublicNoArgConstructor(Class<?> type) {
+      Class<?> current = type.getSuperclass();
+      while (current != null && current != Object.class) {
+        try {
+          Constructor<?> constructor = current.getDeclaredConstructor();
+          if (constructor.getModifiers() == java.lang.reflect.Modifier.PUBLIC) 
{
+            return constructor;
+          }
+        } catch (NoSuchMethodException ignored) {
+          // Continue searching
+        }
+        current = current.getSuperclass();
+      }
+      return null;
+    }
+
+    @Override
+    public T newInstance() {
+      try {
+        return constructor.newInstance();
+      } catch (Exception e) {
+        throw new ForyException(
+            "Failed to create instance, please provide a no-arg constructor 
for " + type, e);
+      }
+    }
+
+    @Override
+    public T newInstanceWithArguments(Object... arguments) {
+      throw new UnsupportedOperationException();
+    }
+  }
+}
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/reflect/ReflectionUtils.java 
b/java/fory-core/src/main/java/org/apache/fory/reflect/ReflectionUtils.java
index 2adcbf333..156a7f0ac 100644
--- a/java/fory-core/src/main/java/org/apache/fory/reflect/ReflectionUtils.java
+++ b/java/fory-core/src/main/java/org/apache/fory/reflect/ReflectionUtils.java
@@ -84,14 +84,12 @@ public class ReflectionUtils {
       return null;
     }
     Constructor[] constructors = clazz.getDeclaredConstructors();
-    if (constructors.length == 0) {
-      return null;
-    } else {
-      return Stream.of(constructors)
-          .filter((c) -> c.getParameterCount() == 0)
-          .findAny()
-          .orElse(null);
+    Constructor ctr = null;
+    if (constructors.length != 0) {
+      ctr =
+          Stream.of(constructors).filter((c) -> c.getParameterCount() == 
0).findAny().orElse(null);
     }
+    return ctr;
   }
 
   private static final ClassValue<MethodHandle> ctrHandleCache =
@@ -123,7 +121,11 @@ public class ReflectionUtils {
   public static MethodHandle getCtrHandle(Class<?> cls, boolean checked) {
     MethodHandle methodHandle = ctrHandleCache.get(cls);
     if (checked && methodHandle == null) {
-      throw new RuntimeException(String.format("Class %s doesn't have a no-arg 
constructor", cls));
+      throw new RuntimeException(
+          String.format(
+              "Class %s doesn't have a no-arg constructor, "
+                  + "please provide a no-arg constructor for the type",
+              cls));
     }
     return methodHandle;
   }
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/resolver/ClassResolver.java 
b/java/fory-core/src/main/java/org/apache/fory/resolver/ClassResolver.java
index d0b974231..ca11984f1 100644
--- a/java/fory-core/src/main/java/org/apache/fory/resolver/ClassResolver.java
+++ b/java/fory-core/src/main/java/org/apache/fory/resolver/ClassResolver.java
@@ -101,6 +101,7 @@ import org.apache.fory.meta.ClassDef;
 import org.apache.fory.meta.ClassSpec;
 import org.apache.fory.meta.Encoders;
 import org.apache.fory.meta.MetaString;
+import org.apache.fory.reflect.ObjectCreators;
 import org.apache.fory.reflect.ReflectionUtils;
 import org.apache.fory.reflect.TypeRef;
 import org.apache.fory.serializer.ArraySerializers;
@@ -1296,6 +1297,7 @@ public class ClassResolver extends TypeResolver {
         RecordUtils.getRecordConstructor(cls);
         RecordUtils.getRecordComponents(cls);
       }
+      ObjectCreators.getObjectCreator(cls);
     }
   }
 
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/serializer/AbstractObjectSerializer.java
 
b/java/fory-core/src/main/java/org/apache/fory/serializer/AbstractObjectSerializer.java
index cb52c5bfb..1dc0703a7 100644
--- 
a/java/fory-core/src/main/java/org/apache/fory/serializer/AbstractObjectSerializer.java
+++ 
b/java/fory-core/src/main/java/org/apache/fory/serializer/AbstractObjectSerializer.java
@@ -21,7 +21,6 @@ package org.apache.fory.serializer;
 
 import static org.apache.fory.type.TypeUtils.getRawType;
 
-import java.lang.invoke.MethodHandle;
 import java.lang.reflect.Field;
 import java.lang.reflect.Modifier;
 import java.util.ArrayList;
@@ -36,6 +35,8 @@ import org.apache.fory.collection.Tuple3;
 import org.apache.fory.memory.MemoryBuffer;
 import org.apache.fory.memory.Platform;
 import org.apache.fory.reflect.FieldAccessor;
+import org.apache.fory.reflect.ObjectCreator;
+import org.apache.fory.reflect.ObjectCreators;
 import org.apache.fory.reflect.ReflectionUtils;
 import org.apache.fory.reflect.TypeRef;
 import org.apache.fory.resolver.ClassInfo;
@@ -57,25 +58,20 @@ public abstract class AbstractObjectSerializer<T> extends 
Serializer<T> {
   protected final RefResolver refResolver;
   protected final ClassResolver classResolver;
   protected final boolean isRecord;
-  protected final MethodHandle constructor;
+  protected final ObjectCreator<T> objectCreator;
   private InternalFieldInfo[] fieldInfos;
   private RecordInfo copyRecordInfo;
 
   public AbstractObjectSerializer(Fory fory, Class<T> type) {
-    this(
-        fory,
-        type,
-        RecordUtils.isRecord(type)
-            ? RecordUtils.getRecordConstructor(type).f1
-            : ReflectionUtils.getCtrHandle(type, false));
+    this(fory, type, ObjectCreators.getObjectCreator(type));
   }
 
-  public AbstractObjectSerializer(Fory fory, Class<T> type, MethodHandle 
constructor) {
+  public AbstractObjectSerializer(Fory fory, Class<T> type, ObjectCreator<T> 
objectCreator) {
     super(fory, type);
     this.refResolver = fory.getRefResolver();
     this.classResolver = fory.getClassResolver();
     this.isRecord = RecordUtils.isRecord(type);
-    this.constructor = constructor;
+    this.objectCreator = objectCreator;
   }
 
   /**
@@ -704,7 +700,7 @@ public abstract class AbstractObjectSerializer<T> extends 
Serializer<T> {
   private T copyRecord(T originObj) {
     Object[] fieldValues = copyFields(originObj);
     try {
-      T t = (T) constructor.invokeWithArguments(fieldValues);
+      T t = (T) objectCreator.newInstanceWithArguments(fieldValues);
       Arrays.fill(copyRecordInfo.getRecordComponents(), null);
       fory.reference(originObj, t);
       return t;
@@ -931,14 +927,7 @@ public abstract class AbstractObjectSerializer<T> extends 
Serializer<T> {
   }
 
   protected T newBean() {
-    if (constructor != null) {
-      try {
-        return (T) constructor.invoke();
-      } catch (Throwable e) {
-        Platform.throwException(e);
-      }
-    }
-    return Platform.newInstance(type);
+    return objectCreator.newInstance();
   }
 
   static Tuple3<Tuple2<FinalTypeField[], boolean[]>, GenericTypeField[], 
GenericTypeField[]>
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/serializer/CompatibleSerializer.java
 
b/java/fory-core/src/main/java/org/apache/fory/serializer/CompatibleSerializer.java
index eb3242239..b5c766fd4 100644
--- 
a/java/fory-core/src/main/java/org/apache/fory/serializer/CompatibleSerializer.java
+++ 
b/java/fory-core/src/main/java/org/apache/fory/serializer/CompatibleSerializer.java
@@ -26,7 +26,6 @@ import java.util.Map;
 import java.util.stream.Collectors;
 import org.apache.fory.Fory;
 import org.apache.fory.memory.MemoryBuffer;
-import org.apache.fory.memory.Platform;
 import org.apache.fory.reflect.FieldAccessor;
 import org.apache.fory.resolver.ClassInfo;
 import org.apache.fory.resolver.ClassResolver;
@@ -69,7 +68,7 @@ public final class CompatibleSerializer<T> extends 
CompatibleSerializerBase<T> {
   }
 
   public CompatibleSerializer(Fory fory, Class<T> cls, FieldResolver 
fieldResolver) {
-    super(fory, cls, null);
+    super(fory, cls);
     Preconditions.checkArgument(!isRecord, cls);
     recordInfo = null;
     this.fieldResolver = fieldResolver;
@@ -309,16 +308,12 @@ public final class CompatibleSerializer<T> extends 
CompatibleSerializerBase<T> {
       Object[] fieldValues = new Object[fieldResolver.getNumFields()];
       readFields(buffer, fieldValues);
       fieldValues = RecordUtils.remapping(recordInfo, fieldValues);
-      assert constructor != null;
-      try {
-        T t = (T) constructor.invokeWithArguments(fieldValues);
-        Arrays.fill(recordInfo.getRecordComponents(), null);
-        return t;
-      } catch (Throwable e) {
-        Platform.throwException(e);
-      }
+      assert objectCreator != null;
+      T t = objectCreator.newInstanceWithArguments(fieldValues);
+      Arrays.fill(recordInfo.getRecordComponents(), null);
+      return t;
     }
-    T obj = (T) newBean();
+    T obj = newBean();
     refResolver.reference(obj);
     return readAndSetFields(buffer, obj);
   }
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/serializer/CompatibleSerializerBase.java
 
b/java/fory-core/src/main/java/org/apache/fory/serializer/CompatibleSerializerBase.java
index 226511643..f318ff73e 100644
--- 
a/java/fory-core/src/main/java/org/apache/fory/serializer/CompatibleSerializerBase.java
+++ 
b/java/fory-core/src/main/java/org/apache/fory/serializer/CompatibleSerializerBase.java
@@ -19,9 +19,9 @@
 
 package org.apache.fory.serializer;
 
-import java.lang.invoke.MethodHandle;
 import org.apache.fory.Fory;
 import org.apache.fory.memory.MemoryBuffer;
+import org.apache.fory.reflect.ObjectCreator;
 
 /**
  * Base class for compatible serializer. Both JIT mode serializer and 
interpreter-mode serializer
@@ -32,8 +32,8 @@ public abstract class CompatibleSerializerBase<T> extends 
AbstractObjectSerializ
     super(fory, type);
   }
 
-  public CompatibleSerializerBase(Fory fory, Class<T> type, MethodHandle 
constructor) {
-    super(fory, type, constructor);
+  public CompatibleSerializerBase(Fory fory, Class<T> type, ObjectCreator<T> 
objectCreator) {
+    super(fory, type, objectCreator);
   }
 
   public T readAndSetFields(MemoryBuffer buffer, T obj) {
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/serializer/ExternalizableSerializer.java
 
b/java/fory-core/src/main/java/org/apache/fory/serializer/ExternalizableSerializer.java
index 081a360e4..2338e6056 100644
--- 
a/java/fory-core/src/main/java/org/apache/fory/serializer/ExternalizableSerializer.java
+++ 
b/java/fory-core/src/main/java/org/apache/fory/serializer/ExternalizableSerializer.java
@@ -21,25 +21,20 @@ package org.apache.fory.serializer;
 
 import java.io.Externalizable;
 import java.io.IOException;
-import java.lang.invoke.MethodHandle;
 import org.apache.fory.Fory;
 import org.apache.fory.io.MemoryBufferObjectInput;
 import org.apache.fory.io.MemoryBufferObjectOutput;
 import org.apache.fory.memory.MemoryBuffer;
 import org.apache.fory.memory.Platform;
-import org.apache.fory.reflect.ReflectionUtils;
 
 /** Serializer for class implements {@link Externalizable}. */
 public class ExternalizableSerializer<T extends Externalizable>
     extends AbstractObjectSerializer<T> {
-  private final MethodHandle constructor;
   private final MemoryBufferObjectInput objectInput;
   private final MemoryBufferObjectOutput objectOutput;
 
   public ExternalizableSerializer(Fory fory, Class<T> cls) {
     super(fory, cls);
-    constructor = ReflectionUtils.getCtrHandle(cls, false);
-
     objectInput = new MemoryBufferObjectInput(fory, null);
     objectOutput = new MemoryBufferObjectOutput(fory, null);
   }
@@ -60,18 +55,9 @@ public class ExternalizableSerializer<T extends 
Externalizable>
   }
 
   @Override
-  @SuppressWarnings("unchecked")
   public T read(MemoryBuffer buffer) {
-    T t;
-    if (constructor != null) {
-      try {
-        t = (T) constructor.invoke();
-      } catch (Throwable e) {
-        throw new RuntimeException(e);
-      }
-    } else {
-      t = Platform.newInstance(type);
-    }
+    T t = objectCreator.newInstance();
+    refResolver.reference(t);
     objectInput.setBuffer(buffer);
     try {
       t.readExternal(objectInput);
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/serializer/MetaSharedSerializer.java
 
b/java/fory-core/src/main/java/org/apache/fory/serializer/MetaSharedSerializer.java
index 7d34dc9cc..7d5272d56 100644
--- 
a/java/fory-core/src/main/java/org/apache/fory/serializer/MetaSharedSerializer.java
+++ 
b/java/fory-core/src/main/java/org/apache/fory/serializer/MetaSharedSerializer.java
@@ -41,6 +41,7 @@ import org.apache.fory.type.Descriptor;
 import org.apache.fory.type.DescriptorGrouper;
 import org.apache.fory.type.Generics;
 import org.apache.fory.util.DefaultValueUtils;
+import org.apache.fory.util.GraalvmSupport;
 import org.apache.fory.util.Preconditions;
 import org.apache.fory.util.record.RecordInfo;
 import org.apache.fory.util.record.RecordUtils;
@@ -162,14 +163,9 @@ public class MetaSharedSerializer<T> extends 
AbstractObjectSerializer<T> {
           new Object[finalFields.length + otherFields.length + 
containerFields.length];
       readFields(buffer, fieldValues);
       fieldValues = RecordUtils.remapping(recordInfo, fieldValues);
-
-      try {
-        T t = (T) constructor.invokeWithArguments(fieldValues);
-        Arrays.fill(recordInfo.getRecordComponents(), null);
-        return t;
-      } catch (Throwable e) {
-        Platform.throwException(e);
-      }
+      T t = objectCreator.newInstanceWithArguments(fieldValues);
+      Arrays.fill(recordInfo.getRecordComponents(), null);
+      return t;
     }
     T obj = newInstance();
     Fory fory = this.fory;
@@ -254,7 +250,7 @@ public class MetaSharedSerializer<T> extends 
AbstractObjectSerializer<T> {
     if (!hasDefaultValues) {
       return newBean();
     }
-    T obj = Platform.newInstance(type);
+    T obj = GraalvmSupport.IN_GRAALVM_NATIVE_IMAGE ? newBean() : 
Platform.newInstance(type);
     // Set default values for missing fields in Scala case classes
     DefaultValueUtils.setDefaultValues(obj, defaultValueFields);
     return obj;
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/serializer/ObjectSerializer.java 
b/java/fory-core/src/main/java/org/apache/fory/serializer/ObjectSerializer.java
index 69edcb4fe..b26ca8ad7 100644
--- 
a/java/fory-core/src/main/java/org/apache/fory/serializer/ObjectSerializer.java
+++ 
b/java/fory-core/src/main/java/org/apache/fory/serializer/ObjectSerializer.java
@@ -29,7 +29,6 @@ import org.apache.fory.collection.Tuple2;
 import org.apache.fory.collection.Tuple3;
 import org.apache.fory.exception.ForyException;
 import org.apache.fory.memory.MemoryBuffer;
-import org.apache.fory.memory.Platform;
 import org.apache.fory.meta.ClassDef;
 import org.apache.fory.reflect.FieldAccessor;
 import org.apache.fory.reflect.ReflectionUtils;
@@ -245,13 +244,9 @@ public final class ObjectSerializer<T> extends 
AbstractObjectSerializer<T> {
     if (isRecord) {
       Object[] fields = readFields(buffer);
       fields = RecordUtils.remapping(recordInfo, fields);
-      try {
-        T obj = (T) constructor.invokeWithArguments(fields);
-        Arrays.fill(recordInfo.getRecordComponents(), null);
-        return obj;
-      } catch (Throwable e) {
-        Platform.throwException(e);
-      }
+      T obj = (T) objectCreator.newInstanceWithArguments(fields);
+      Arrays.fill(recordInfo.getRecordComponents(), null);
+      return obj;
     }
     T obj = newBean();
     refResolver.reference(obj);
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/serializer/ObjectStreamSerializer.java
 
b/java/fory-core/src/main/java/org/apache/fory/serializer/ObjectStreamSerializer.java
index ef672d9b7..efc18543f 100644
--- 
a/java/fory-core/src/main/java/org/apache/fory/serializer/ObjectStreamSerializer.java
+++ 
b/java/fory-core/src/main/java/org/apache/fory/serializer/ObjectStreamSerializer.java
@@ -34,7 +34,6 @@ import java.io.ObjectStreamField;
 import java.io.Serializable;
 import java.io.UnsupportedEncodingException;
 import java.lang.invoke.MethodHandles;
-import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.util.ArrayList;
@@ -81,7 +80,6 @@ import org.apache.fory.util.unsafe._JDKAccess;
 public class ObjectStreamSerializer extends AbstractObjectSerializer {
   private static final Logger LOG = 
LoggerFactory.getLogger(ObjectStreamSerializer.class);
 
-  private final Constructor constructor;
   private final SlotsInfo[] slotsInfos;
 
   public ObjectStreamSerializer(Fory fory, Class<?> type) {
@@ -98,17 +96,6 @@ public class ObjectStreamSerializer extends 
AbstractObjectSerializer {
         Externalizable.class.getName());
     // stream serializer may be data serializer of ReplaceResolver serializer.
     fory.getClassResolver().setSerializerIfAbsent(type, this);
-    Constructor constructor;
-    try {
-      constructor = type.getConstructor();
-      if (!constructor.isAccessible()) {
-        constructor.setAccessible(true);
-      }
-    } catch (Exception e) {
-      constructor =
-          (Constructor) 
ReflectionUtils.getObjectFieldValue(ObjectStreamClass.lookup(type), "cons");
-    }
-    this.constructor = constructor;
     List<SlotsInfo> slotsInfoList = new ArrayList<>();
     Class<?> end = type;
     // locate closest non-serializable superclass
@@ -166,16 +153,7 @@ public class ObjectStreamSerializer extends 
AbstractObjectSerializer {
 
   @Override
   public Object read(MemoryBuffer buffer) {
-    Object obj = null;
-    if (constructor != null) {
-      try {
-        obj = constructor.newInstance();
-      } catch (InstantiationException | IllegalAccessException | 
InvocationTargetException e) {
-        Platform.throwException(e);
-      }
-    } else {
-      obj = Platform.newInstance(type);
-    }
+    Object obj = objectCreator.newInstance();
     fory.getRefResolver().reference(obj);
     int numClasses = buffer.readInt16();
     int slotIndex = 0;
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/util/GraalvmSupport.java 
b/java/fory-core/src/main/java/org/apache/fory/util/GraalvmSupport.java
index edf00db99..7bfe2b00b 100644
--- a/java/fory-core/src/main/java/org/apache/fory/util/GraalvmSupport.java
+++ b/java/fory-core/src/main/java/org/apache/fory/util/GraalvmSupport.java
@@ -19,8 +19,11 @@
 
 package org.apache.fory.util;
 
+import java.lang.reflect.Constructor;
 import java.util.Objects;
 import org.apache.fory.Fory;
+import org.apache.fory.exception.ForyException;
+import org.apache.fory.memory.MemoryBuffer;
 import org.apache.fory.serializer.Serializer;
 
 /** A helper for Graalvm native image support. */
@@ -53,6 +56,7 @@ public class GraalvmSupport {
 
   public static class GraalvmSerializerHolder extends Serializer {
     private final Class serializerClass;
+    private Serializer serializer;
 
     public GraalvmSerializerHolder(Fory fory, Class<?> type, Class<?> 
serializerClass) {
       super(fory, type);
@@ -62,5 +66,34 @@ public class GraalvmSupport {
     public Class<? extends Serializer> getSerializerClass() {
       return serializerClass;
     }
+
+    @Override
+    public void write(MemoryBuffer buffer, Object value) {
+      // for debug only, graalvm native image won't go to here
+      getSerializer().write(buffer, value);
+    }
+
+    @Override
+    public Object read(MemoryBuffer buffer) {
+      // for debug only, graalvm native image won't go to here
+      return getSerializer().read(buffer);
+    }
+
+    private Serializer getSerializer() {
+      if (serializer == null) {
+        try {
+          Constructor ctr = serializerClass.getDeclaredConstructor(Fory.class, 
Class.class);
+          ctr.setAccessible(true);
+          serializer = (Serializer) ctr.newInstance(fory, type);
+        } catch (Exception e) {
+          throw new RuntimeException(e);
+        }
+      }
+      return serializer;
+    }
+  }
+
+  public static ForyException throwNoArgCtrException(Class<?> type) {
+    throw new ForyException("Please provide a no-arg constructor for " + type);
   }
 }
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/util/record/RecordUtils.java 
b/java/fory-core/src/main/java/org/apache/fory/util/record/RecordUtils.java
index 176d42a69..617e26bc1 100644
--- a/java/fory-core/src/main/java/org/apache/fory/util/record/RecordUtils.java
+++ b/java/fory-core/src/main/java/org/apache/fory/util/record/RecordUtils.java
@@ -203,15 +203,6 @@ public class RecordUtils {
     return getRecordConstructor(cls).f1;
   }
 
-  // Invoked by jit
-  public static Object invokeRecordCtrHandle(MethodHandle handle, Object[] 
fields) {
-    try {
-      return handle.invokeWithArguments(fields);
-    } catch (Throwable e) {
-      throw new RuntimeException(e);
-    }
-  }
-
   public static Object[] buildRecordComponentDefaultValues(Class<?> cls) {
     RecordComponent[] components = RecordUtils.getRecordComponents(cls);
     assert components != null;
diff --git 
a/java/fory-core/src/main/resources/META-INF/native-image/org.apache.fory/fory-core/native-image.properties
 
b/java/fory-core/src/main/resources/META-INF/native-image/org.apache.fory/fory-core/native-image.properties
index 8796e6db0..773687906 100644
--- 
a/java/fory-core/src/main/resources/META-INF/native-image/org.apache.fory/fory-core/native-image.properties
+++ 
b/java/fory-core/src/main/resources/META-INF/native-image/org.apache.fory/fory-core/native-image.properties
@@ -266,6 +266,11 @@ 
Args=--initialize-at-build-time=org.apache.fory.memory.MemoryBuffer,\
     org.apache.fory.reflect.TypeRef$ClassOwnership,\
     org.apache.fory.reflect.TypeRef$TypeVariableKey,\
     org.apache.fory.reflect.TypeRef,\
+    org.apache.fory.reflect.ObjectCreators,\
+    org.apache.fory.reflect.ObjectCreators$UnsafeObjectCreator,\
+    org.apache.fory.reflect.ObjectCreators$DeclaredNoArgCtrObjectCreator,\
+    org.apache.fory.reflect.ObjectCreators$ParentNoArgCtrObjectCreator,\
+    org.apache.fory.reflect.ObjectCreators$RecordObjectCreator,\
     org.apache.fory.resolver.ClassChecker,\
     org.apache.fory.resolver.TypeChecker,\
     org.apache.fory.resolver.ClassInfo,\
diff --git 
a/java/fory-core/src/main/java/org/apache/fory/serializer/CompatibleSerializerBase.java
 b/java/fory-core/src/test/java/org/apache/fory/reflect/ObjectCreatorsTest.java
similarity index 50%
copy from 
java/fory-core/src/main/java/org/apache/fory/serializer/CompatibleSerializerBase.java
copy to 
java/fory-core/src/test/java/org/apache/fory/reflect/ObjectCreatorsTest.java
index 226511643..c30182ee0 100644
--- 
a/java/fory-core/src/main/java/org/apache/fory/serializer/CompatibleSerializerBase.java
+++ 
b/java/fory-core/src/test/java/org/apache/fory/reflect/ObjectCreatorsTest.java
@@ -17,27 +17,31 @@
  * under the License.
  */
 
-package org.apache.fory.serializer;
+package org.apache.fory.reflect;
 
-import java.lang.invoke.MethodHandle;
-import org.apache.fory.Fory;
-import org.apache.fory.memory.MemoryBuffer;
+import java.util.concurrent.ArrayBlockingQueue;
+import org.apache.fory.reflect.ObjectCreators.ParentNoArgCtrObjectCreator;
+import org.testng.Assert;
+import org.testng.annotations.Test;
 
-/**
- * Base class for compatible serializer. Both JIT mode serializer and 
interpreter-mode serializer
- * will extend this class.
- */
-public abstract class CompatibleSerializerBase<T> extends 
AbstractObjectSerializer<T> {
-  public CompatibleSerializerBase(Fory fory, Class<T> type) {
-    super(fory, type);
-  }
+@SuppressWarnings("rawtypes")
+public class ObjectCreatorsTest {
+
+  static class NoCtrTestClass {
+    int f1;
 
-  public CompatibleSerializerBase(Fory fory, Class<T> type, MethodHandle 
constructor) {
-    super(fory, type, constructor);
+    public NoCtrTestClass(int f1) {
+      this.f1 = f1;
+    }
   }
 
-  public T readAndSetFields(MemoryBuffer buffer, T obj) {
-    // java record object doesn't support update state.
-    throw new UnsupportedOperationException();
+  @Test
+  public void testObjectCreator() {
+    ParentNoArgCtrObjectCreator<ArrayBlockingQueue> creator =
+        new ParentNoArgCtrObjectCreator<>(ArrayBlockingQueue.class);
+    Assert.assertEquals(creator.newInstance().getClass(), 
ArrayBlockingQueue.class);
+    Assert.assertEquals(
+        new 
ParentNoArgCtrObjectCreator<>(NoCtrTestClass.class).newInstance().getClass(),
+        NoCtrTestClass.class);
   }
 }
diff --git 
a/java/fory-core/src/test/java/org/apache/fory/reflect/ReflectionUtilsTest.java 
b/java/fory-core/src/test/java/org/apache/fory/reflect/ReflectionUtilsTest.java
index 501a77789..6dc2b0fa4 100644
--- 
a/java/fory-core/src/test/java/org/apache/fory/reflect/ReflectionUtilsTest.java
+++ 
b/java/fory-core/src/test/java/org/apache/fory/reflect/ReflectionUtilsTest.java
@@ -24,6 +24,8 @@ import static org.testng.Assert.assertFalse;
 import static org.testng.Assert.assertTrue;
 
 import com.google.common.collect.ImmutableList;
+import java.io.Serializable;
+import java.lang.reflect.Constructor;
 import java.util.List;
 import org.apache.fory.test.bean.BeanA;
 import org.apache.fory.type.Descriptor;
@@ -101,4 +103,29 @@ public class ReflectionUtilsTest {
     
Assert.assertTrue(ReflectionUtils.isMonomorphic(MonomorphicTestEnum1[].class));
     
Assert.assertTrue(ReflectionUtils.isMonomorphic(MonomorphicTestEnum2[].class));
   }
+
+  static class NoArgConstructor1 implements Serializable {
+    int f1;
+
+    public NoArgConstructor1(int f1) {
+      this.f1 = f1;
+    }
+  }
+
+  @Test
+  public void testGetNoArgConstructor() throws Throwable {
+    Constructor ctr = 
ReflectionUtils.getNoArgConstructor(NoArgConstructor1.class);
+    Assert.assertNull(ctr);
+
+    // ctr is generated by 
jdk.internal.reflect.ReflectionFactory.generateConstructor,
+    // `unreflectConstructor` doesn't work, see ParentNoArgCtrObjectCreator to 
get parent no-arg
+    // ctr.
+    // MethodHandle handle = lookup.unreflectConstructor(ctr);
+    // System.out.println(ctr);
+    // System.out.println(handle);
+    // org.apache.fory.reflect.ReflectionUtilsTest$NoArgConstructor1@4d339552
+    // System.out.println(ctr.newInstance());
+    // java.lang.Object@f0f2775
+    // System.out.println(handle.invoke());
+  }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to