HHH-15595 ClassLoadingStrategyHelper no longer needs to use reflection to be compatible with Java 8

This commit is contained in:
Sanne Grinovero 2022-10-11 21:59:26 +01:00 committed by Sanne Grinovero
parent 7a1d27e28a
commit 622273aeb2
1 changed files with 2 additions and 34 deletions

View File

@ -7,13 +7,9 @@
package org.hibernate.bytecode.spi; package org.hibernate.bytecode.spi;
import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.internal.CoreMessageLogger;
import net.bytebuddy.dynamic.loading.ClassInjector;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import static org.hibernate.internal.CoreLogging.messageLogger; import static org.hibernate.internal.CoreLogging.messageLogger;
@ -21,41 +17,13 @@ import static org.hibernate.internal.CoreLogging.messageLogger;
public class ClassLoadingStrategyHelper { public class ClassLoadingStrategyHelper {
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
private static final CoreMessageLogger LOG = messageLogger( ClassLoadingStrategyHelper.class );
public static ClassLoadingStrategy<ClassLoader> resolveClassLoadingStrategy(Class<?> originalClass) { public static ClassLoadingStrategy<ClassLoader> resolveClassLoadingStrategy(Class<?> originalClass) {
// This is available only for JDK 9+
if ( !ClassInjector.UsingLookup.isAvailable() ) {
return new ClassLoadingStrategy.ForUnsafeInjection( originalClass.getProtectionDomain() );
}
Method privateLookupIn;
try { try {
privateLookupIn = MethodHandles.class.getMethod( "privateLookupIn", Class.class, MethodHandles.Lookup.class ); return ClassLoadingStrategy.UsingLookup.of( MethodHandles.privateLookupIn( originalClass, LOOKUP ) );
}
catch (Exception e) {
throw new HibernateException( LOG.bytecodeEnhancementFailed( originalClass.getName() ), e );
}
try {
Object privateLookup;
try {
privateLookup = privateLookupIn.invoke( null, originalClass, LOOKUP );
}
catch (InvocationTargetException exception) {
if ( exception.getCause() instanceof IllegalAccessException ) {
return new ClassLoadingStrategy.ForUnsafeInjection( originalClass.getProtectionDomain() );
}
else {
throw new HibernateException( LOG.bytecodeEnhancementFailed( originalClass.getName() ), exception.getCause() );
}
}
return ClassLoadingStrategy.UsingLookup.of( privateLookup );
} }
catch (Throwable e) { catch (Throwable e) {
throw new HibernateException( LOG.bytecodeEnhancementFailedUnableToGetPrivateLookupFor( originalClass.getName() ), e ); throw new HibernateException( messageLogger( ClassLoadingStrategyHelper.class ).bytecodeEnhancementFailedUnableToGetPrivateLookupFor( originalClass.getName() ), e );
} }
} }