Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 26 additions & 10 deletions src/main/java/org/apache/ibatis/binding/MapperProxy.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import java.io.Serializable;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
Expand All @@ -32,6 +33,9 @@
public class MapperProxy<T> implements InvocationHandler, Serializable {

private static final long serialVersionUID = -6424540398559729838L;
private static final int ALLOWED_MODES = MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED
| MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC;
private static Constructor<Lookup> lookupConstructor;
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache;
Expand All @@ -42,6 +46,20 @@ public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method,
this.methodCache = methodCache;
}

static {
try {
lookupConstructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, int.class);
} catch (NoSuchMethodException e) {
try {
// Since Java 14+8
lookupConstructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, Class.class, int.class);
} catch (NoSuchMethodException e2) {
throw new IllegalStateException("No known constructor found in java.lang.invoke.MethodHandles.Lookup.", e2);
}
}
lookupConstructor.setAccessible(true);
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Expand All @@ -63,16 +81,14 @@ private MapperMethod cachedMapperMethod(Method method) {

private Object invokeDefaultMethod(Object proxy, Method method, Object[] args)
throws Throwable {
final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class
.getDeclaredConstructor(Class.class, int.class);
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
final Class<?> declaringClass = method.getDeclaringClass();
return constructor
.newInstance(declaringClass,
MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED
| MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC)
.unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
final Lookup lookup;
if (lookupConstructor.getParameterCount() == 2) {
lookup = lookupConstructor.newInstance(declaringClass, ALLOWED_MODES);
} else {
// SInce JDK 14+8
lookup = lookupConstructor.newInstance(declaringClass, null, ALLOWED_MODES);
}
return lookup.unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
}
}