我有这个工作正常的代码:
Method getterMethod = Person.class.getDeclaredMethod("getName");
MethodHandles.Lookup lookup = MethodHandles.publicLookup();
Class<?> declaringClass = getterMethod.getDeclaringClass();
Class<?> returnType = getterMethod.getReturnType();
CallSite getterSite = LambdaMetafactory.metafactory(lookup,
"apply",
MethodType.methodType(Function.class),
MethodType.methodType(Object.class, Object.class),
lookup.findVirtual(declaringClass, getterMethod.getName(), MethodType.methodType(returnType)),
MethodType.methodType(propertyType, declaringClass));
Function getterFunction = (Function) getterSite.getTarget().invokeExact();
但是如果getterMethod
是从不同的 ClassLoader 加载的类的方法,它会抛出:
Caused by: java.lang.invoke.LambdaConversionException: Invalid caller: java.lang.Object
at java.lang.invoke.AbstractValidatingLambdaMetafactory.<init>(AbstractValidatingLambdaMetafactory.java:118)
at java.lang.invoke.InnerClassLambdaMetafactory.<init>(InnerClassLambdaMetafactory.java:155)
at java.lang.invoke.LambdaMetafactory.metafactory(LambdaMetafactory.java:299)
如何将我的ClassLoader
实例传递给LambdaMetafactory
?