From e2b24f3c12c46546eed7668197ef747cb0345f14 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Tue, 11 Jul 2023 17:50:44 +0200 Subject: [PATCH] Improve diagnostics for LinkageError in case of ClassLoader mismatch Closes gh-25940 --- .../cglib/core/ReflectUtils.java | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/cglib/core/ReflectUtils.java b/spring-core/src/main/java/org/springframework/cglib/core/ReflectUtils.java index 3efb7663c3b1..9bd022ccee57 100644 --- a/spring-core/src/main/java/org/springframework/cglib/core/ReflectUtils.java +++ b/spring-core/src/main/java/org/springframework/cglib/core/ReflectUtils.java @@ -22,6 +22,7 @@ import java.beans.PropertyDescriptor; import java.lang.invoke.MethodHandles; import java.lang.reflect.Constructor; +import java.lang.reflect.InaccessibleObjectException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; @@ -508,14 +509,14 @@ public static Class defineClass(String className, byte[] b, ClassLoader loader, catch (InvocationTargetException ex) { throw new CodeGenerationException(ex.getTargetException()); } - catch (Throwable ex) { - // Fall through if setAccessible fails with InaccessibleObjectException on JDK 9+ - // (on the module path and/or with a JVM bootstrapped with --illegal-access=deny) - if (!ex.getClass().getName().endsWith("InaccessibleObjectException")) { - throw new CodeGenerationException(ex); - } + catch (InaccessibleObjectException ex) { + // setAccessible failed with JDK 9+ InaccessibleObjectException -> fall through + // Avoid through JVM startup with --add-opens=java.base/java.lang=ALL-UNNAMED t = ex; } + catch (Throwable ex) { + throw new CodeGenerationException(ex); + } } } @@ -525,13 +526,14 @@ public static Class defineClass(String className, byte[] b, ClassLoader loader, MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(contextClass, MethodHandles.lookup()); c = lookup.defineClass(b); } - catch (IllegalAccessException ex) { + catch (LinkageError | IllegalAccessException ex) { throw new CodeGenerationException(ex) { @Override public String getMessage() { return "ClassLoader mismatch for [" + contextClass.getName() + "]: JVM should be started with --add-opens=java.base/java.lang=ALL-UNNAMED " + - "for ClassLoader.defineClass to be accessible on " + loader.getClass().getName(); + "for ClassLoader.defineClass to be accessible on " + loader.getClass().getName() + + "; consider co-locating the affected class in that target ClassLoader instead."; } }; }