This is an automated email from the ASF dual-hosted git repository.
garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git
The following commit(s) were added to refs/heads/master by this push:
new c44f56692 Preserve class loaders in SerializationUtils.clone and
roundtrip
c44f56692 is described below
commit c44f56692bd553aa87d23a3bb29c182f06e8459b
Author: Gary Gregory <[email protected]>
AuthorDate: Wed Nov 18 11:15:17 2026 -0500
Preserve class loaders in SerializationUtils.clone and roundtrip
Delegate roundtrip() to clone() and record original classes during
serialization. Resolve class descriptors using their recorded identities
to preserve same-named classes from different loaders throughout object
graphs, including proxy invocation handlers.
Add regressions for isolated and plugin-only classes, mixed-loader
collections, class objects, arrays, and shared references. Update
Javadoc.
Assisted-By: OpenAI Codex
---
src/changes/changes.xml | 1 +
.../apache/commons/lang3/SerializationUtils.java | 79 +++++++---------
.../commons/lang3/SerializationUtilsTest.java | 105 +++++++++++++++++++++
3 files changed, 141 insertions(+), 44 deletions(-)
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 6f4f35f17..405fc6cf1 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -104,6 +104,7 @@ The <action> type attribute can be add,update,fix,remove.
<action type="fix" dev="ggregory" due-to="Gary Gregory,
Amar Ghugare">Restrict MethodUtils.invokeStaticMethod to static overloads; both
static invocation variants now throw NoSuchMethodException instead of
NullPointerException when only an instance method matches (#1881).</action>
<action type="fix" dev="ggregory" due-to="Gary Gregory,
Amar Ghugare">Handle Object methods locally in EventListenerSupport proxies,
preventing NullPointerException from equals and hashCode and returning an
identity string from toString.</action>
<action type="fix" dev="ggregory" due-to="Gary Gregory,
Amar Ghugare">Preserve negative durations in DurationUtils.accept so
ThreadUtils.sleep, ThreadUtils.sleepQuietly, ThreadUtils.join, and
ObjectUtils.wait reject negative sub-millisecond timeouts (#1882).</action>
+ <action type="fix" dev="ggregory" due-to="Gary Gregory,
Amar Ghugare">Preserve defining class loaders throughout object graphs in
SerializationUtils.clone() and roundtrip().</action>
<!-- ADD -->
<!-- UPDATE -->
</release>
diff --git a/src/main/java/org/apache/commons/lang3/SerializationUtils.java
b/src/main/java/org/apache/commons/lang3/SerializationUtils.java
index 0d0396130..ce6bc9982 100644
--- a/src/main/java/org/apache/commons/lang3/SerializationUtils.java
+++ b/src/main/java/org/apache/commons/lang3/SerializationUtils.java
@@ -58,14 +58,11 @@
public class SerializationUtils {
/**
- * Custom specialization of the standard JDK {@link ObjectInputStream}
that uses a custom {@link ClassLoader} to resolve classes.
- * If the specified {@link ClassLoader} cannot resolve a class, the
context classloader of the current thread will be used.
- * This way, the standard deserialization
- * also works in web application containers and application servers,
regardless of which {@link ClassLoader} loaded the class that encapsulates
- * serialization/deserialization.
+ * Custom specialization of the standard JDK {@link ObjectInputStream}
that resolves classes to their original definitions.
*
* <p>
- * Proxy classes are recorded during serialization and reused directly to
preserve their defining class loaders without looking up their interfaces.
+ * Classes, including proxy classes, are recorded during serialization and
reused directly to preserve their defining class loaders. Each class descriptor
+ * contains an index into the recorded classes, distinguishing classes
with identical names from different loaders in the same object graph.
* </p>
*
* <p>
@@ -74,54 +71,36 @@ public class SerializationUtils {
*/
static final class ClassLoaderAwareObjectInputStream extends
ObjectInputStream {
- private final ClassLoader classLoader;
-
- private final List<Class<?>> proxyClasses;
+ private final List<Class<?>> classes;
/**
* Constructs a new instance.
*
- * @param in The {@link InputStream}.
- * @param classLoader The class loader to use.
- * @param proxyClasses The proxy classes recorded while serializing
the original object.
+ * @param in The {@link InputStream}.
+ * @param classes The classes recorded while serializing the original
object.
* @throws IOException Thrown if an I/O error occurs while reading
stream header.
* @see java.io.ObjectInputStream
*/
- ClassLoaderAwareObjectInputStream(final InputStream in, final
ClassLoader classLoader, final List<Class<?>> proxyClasses) throws IOException {
+ ClassLoaderAwareObjectInputStream(final InputStream in, final
List<Class<?>> classes) throws IOException {
super(in);
- this.classLoader = classLoader;
- this.proxyClasses = proxyClasses;
+ this.classes = classes;
}
/**
- * Overridden version that uses the parameterized {@link ClassLoader}
or the {@link ClassLoader} of the current {@link Thread} to resolve the class.
+ * Resolves a class using its recorded identity.
*
* @param desc An instance of class {@link ObjectStreamClass}.
* @return A {@link Class} object corresponding to {@code desc}.
* @throws IOException Thrown if an I/O error occurs.
- * @throws ClassNotFoundException Thrown if class of a serialized
object cannot be found.
*/
@Override
- protected Class<?> resolveClass(final ObjectStreamClass desc) throws
IOException, ClassNotFoundException {
- final String name = desc.getName();
- try {
- return Class.forName(name, false, classLoader);
- } catch (final ClassNotFoundException ex) {
- try {
- return Class.forName(name, false,
Thread.currentThread().getContextClassLoader());
- } catch (final ClassNotFoundException cnfe) {
- final Class<?> cls = ClassUtils.getPrimitiveClass(name);
- if (cls != null) {
- return cls;
- }
- throw cnfe;
- }
- }
+ protected Class<?> resolveClass(final ObjectStreamClass desc) throws
IOException {
+ return classes.get(readInt());
}
@Override
protected Class<?> resolveProxyClass(final String[] interfaces) throws
IOException {
- return proxyClasses.get(readInt());
+ return classes.get(readInt());
}
}
@@ -133,6 +112,10 @@ protected Class<?> resolveProxyClass(final String[]
interfaces) throws IOExcepti
* don't support deep cloning this can be a simple alternative
implementation. Of course all the objects must be {@link Serializable}.
* </p>
*
+ * <p>
+ * Resolves serialized classes and proxy classes to their original
definitions, preserving their defining class loaders.
+ * </p>
+ *
* @param <T> the type of the object involved.
* @param object The {@link Serializable} object to clone.
* @return The cloned object.
@@ -144,13 +127,18 @@ public static <T extends Serializable> T clone(final T
object) {
return null;
}
final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
- final List<Class<?>> proxyClasses = new ArrayList<>();
+ final List<Class<?>> classes = new ArrayList<>();
try (ObjectOutputStream out = new ObjectOutputStream(baos) {
+ @Override
+ protected void annotateClass(final Class<?> cls) throws
IOException {
+ // Pair each descriptor with its original class, even when
another loader defines the same name.
+ writeInt(classes.size());
+ classes.add(cls);
+ }
+
@Override
protected void annotateProxyClass(final Class<?> proxyClass)
throws IOException {
- // Pair the descriptor with its original class, even when
another loader defines the same interface names.
- writeInt(proxyClasses.size());
- proxyClasses.add(proxyClass);
+ annotateClass(proxyClass);
}
}) {
out.writeObject(object);
@@ -158,8 +146,7 @@ protected void annotateProxyClass(final Class<?>
proxyClass) throws IOException
throw new SerializationException(ex);
}
final ByteArrayInputStream bais = new
ByteArrayInputStream(baos.toByteArray());
- final Class<T> cls = ObjectUtils.getClass(object);
- try (ClassLoaderAwareObjectInputStream in = new
ClassLoaderAwareObjectInputStream(bais, cls.getClassLoader(), proxyClasses)) {
+ try (ClassLoaderAwareObjectInputStream in = new
ClassLoaderAwareObjectInputStream(bais, classes)) {
// When we serialize and deserialize an object, it is reasonable
to assume the deserialized object is of the
// same type as the original serialized object
return (T) in.readObject();
@@ -260,15 +247,19 @@ public static <T> T requireNonNull(final T obj, final
String message) throws Inv
/**
* Performs a serialization roundtrip. Serializes and deserializes the
given object, great for testing objects that implement {@link Serializable}.
*
+ * <p>
+ * Uses {@link #clone(Serializable)} to preserve the defining class
loaders of serialized classes and proxy classes.
+ * </p>
+ *
* @param <T> The type of the object involved.
- * @param obj The object to roundtrip.
- * @return The serialized and deserialized object.
- * @see <a
href="https://docs.oracle.com/en/java/javase/25/docs/specs/serialization/">Java
Object Serialization Specification</a>
+ * @param obj The object to roundtrip, may be {@code null}.
+ * @return The serialized and deserialized object, or {@code null} if the
input is {@code null}.
+ * @throws SerializationException Thrown if serialization or
deserialization fails.
* @since 3.3
+ * @see <a
href="https://docs.oracle.com/en/java/javase/25/docs/specs/serialization/">Java
Object Serialization Specification</a>
*/
- @SuppressWarnings("unchecked") // OK, because we serialized a type `T`
public static <T extends Serializable> T roundtrip(final T obj) {
- return (T) deserialize(serialize(obj));
+ return clone(obj);
}
/**
diff --git a/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
b/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
index 4666f8a93..eff3cc87d 100644
--- a/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
@@ -37,6 +37,7 @@
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
+import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
@@ -159,6 +160,81 @@ void testClone() {
assertEquals(iMap, testMap);
}
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testCloneAndRoundtripClassesFromDifferentClassLoaders(final boolean
roundtrip) throws Exception {
+ final URL[] urls = {
getClass().getProtectionDomain().getCodeSource().getLocation() };
+ final ClassLoader applicationLoader = getClass().getClassLoader();
+ try (URLClassLoader first = new URLClassLoader(urls, null);
+ URLClassLoader second = new URLClassLoader(urls, null)) {
+ final Class<?> firstClass =
Class.forName(ProxyHolder.class.getName(), true, first);
+ final Class<?> secondClass =
Class.forName(ProxyHolder.class.getName(), true, second);
+ final Serializable firstValue = (Serializable)
firstClass.getConstructor(Serializable.class).newInstance("first");
+ final Serializable secondValue = (Serializable)
secondClass.getConstructor(Serializable.class).newInstance("second");
+ final Serializable array = (Serializable)
Array.newInstance(firstClass, 1);
+ Array.set(array, 0, firstValue);
+ final ArrayList<Serializable> values = new ArrayList<>();
+ values.add(new ProxyHolder("application"));
+ values.add(firstValue);
+ values.add(secondValue);
+ values.add(firstClass);
+ values.add(secondClass);
+ values.add(firstValue);
+ values.add(array);
+ for (final ClassLoader contextLoader : new ClassLoader[] {
applicationLoader, first, new ClassLoader(null) { }, null }) {
+ contextClassLoader.setContextClassLoader(contextLoader);
+ final ArrayList<Serializable> copy = roundtrip ?
SerializationUtils.roundtrip(values) : SerializationUtils.clone(values);
+ assertNotSame(values, copy);
+ assertEquals(values.size(), copy.size());
+ for (int i = 0; i < 3; i++) {
+ assertNotSame(values.get(i), copy.get(i));
+ assertSame(values.get(i).getClass(),
copy.get(i).getClass());
+ }
+ assertEquals("application", ((ProxyHolder) copy.get(0)).value);
+ assertEquals("first",
firstClass.getField("value").get(copy.get(1)));
+ assertEquals("second",
secondClass.getField("value").get(copy.get(2)));
+ assertSame(firstClass, copy.get(3));
+ assertSame(secondClass, copy.get(4));
+ assertSame(copy.get(1), copy.get(5));
+ assertNotSame(array, copy.get(6));
+ assertSame(array.getClass(), copy.get(6).getClass());
+ assertSame(copy.get(1), Array.get(copy.get(6), 0));
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testCloneAndRoundtripWithPluginOnlyClass(final boolean roundtrip,
@TempDir final Path tempDir) throws Exception {
+ final String className = "plugin.RoundtripValue";
+ final Path source = tempDir.resolve("RoundtripValue.java");
+ Files.write(source, ("package plugin; public class RoundtripValue
implements java.io.Serializable {"
+ + " private static final long serialVersionUID = 1L; public
String value = \"value\"; }").getBytes(StandardCharsets.UTF_8));
+ final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+ assertNotNull(compiler, "A JDK compiler is required to create the
plugin-only class");
+ final ByteArrayOutputStream diagnostics = new ByteArrayOutputStream();
+ assertEquals(0, compiler.run(null, diagnostics, diagnostics, "-d",
tempDir.toString(), source.toString()),
+ diagnostics.toString(StandardCharsets.UTF_8.name()));
+ final ClassLoader applicationLoader = getClass().getClassLoader();
+ try (URLClassLoader loader = new URLClassLoader(new URL[] {
tempDir.toUri().toURL() }, null)) {
+ contextClassLoader.setContextClassLoader(applicationLoader);
+ assertThrows(ClassNotFoundException.class, () ->
Class.forName(className, false, applicationLoader));
+ final Class<?> valueClass = Class.forName(className, true, loader);
+ final Serializable value = (Serializable)
valueClass.getConstructor().newInstance();
+ final Serializable copy = roundtrip ?
SerializationUtils.roundtrip(value) : SerializationUtils.clone(value);
+ assertNotSame(value, copy);
+ assertSame(valueClass, copy.getClass());
+ assertEquals("value", valueClass.getField("value").get(copy));
+ final ArrayList<Serializable> values = new ArrayList<>();
+ values.add(value);
+ final ArrayList<Serializable> copies = roundtrip ?
SerializationUtils.roundtrip(values) : SerializationUtils.clone(values);
+ assertNotSame(values, copies);
+ assertNotSame(value, copies.get(0));
+ assertSame(valueClass, copies.get(0).getClass());
+ assertEquals("value",
valueClass.getField("value").get(copies.get(0)));
+ }
+ }
+
@Test
void testCloneClassNotFound() {
final SerializationException ex =
assertThrows(SerializationException.class, () -> SerializationUtils.clone(new
ClassNotFoundSerialization()));
@@ -509,6 +585,35 @@ void testPrimitiveTypeClassSerialization() {
void testRoundtrip() {
final HashMap<Object, Object> newMap =
SerializationUtils.roundtrip(iMap);
assertEquals(iMap, newMap);
+ assertNull(SerializationUtils.roundtrip(null));
+ }
+
+ @Test
+ void testRoundtripPreservesClassLoader() throws Exception {
+ final URL[] urls = {
getClass().getProtectionDomain().getCodeSource().getLocation() };
+ try (URLClassLoader loader = new URLClassLoader(urls, null)) {
+ final Class<?> holderClass =
Class.forName(ProxyHolder.class.getName(), true, loader);
+ final Serializable holder = (Serializable)
holderClass.getConstructor(Serializable.class).newInstance("value");
+ final Serializable copy = SerializationUtils.roundtrip(holder);
+ assertNotSame(holder, copy);
+ assertSame(holderClass, copy.getClass());
+ assertEquals("value", holderClass.getField("value").get(copy));
+ }
+ }
+
+ @Test
+ void testRoundtripProxyPreservesClassLoader() throws Exception {
+ final URL[] urls = {
getClass().getProtectionDomain().getCodeSource().getLocation() };
+ try (URLClassLoader loader = new URLClassLoader(urls, null)) {
+ final Class<?> proxyInterface = Class.forName(Bar.class.getName(),
true, loader);
+ final Serializable proxy = (Serializable)
Proxy.newProxyInstance(loader, new Class<?>[] { proxyInterface }, new
SerializableInvocationHandler());
+ final Serializable copy = SerializationUtils.roundtrip(proxy);
+ assertNotSame(proxy, copy);
+ assertSame(proxy.getClass(), copy.getClass());
+ assertNotSame(Proxy.getInvocationHandler(proxy),
Proxy.getInvocationHandler(copy));
+ assertSame(Proxy.getInvocationHandler(proxy).getClass(),
Proxy.getInvocationHandler(copy).getClass());
+ assertEquals("test", copy.toString());
+ }
}
@Test