如何使用 LambdaMetaFactory 为 SAM/功能接口创建代理对象
IE。相当于
public static Object java.lang.reflect.Proxy.newProxyInstance(ClassLoader, Class<?>[], InvocationHandler)
例如。我有多个工厂接口
interface X{
// members
// methods
}
interface Y{
// members
// methods
}
public interface Factory1{
X get(String name);
}
public interface Factory2{
Y get(String name);
}
.
.
.
public interface FactoryN{
someclassOrInterface get(String name);
}
我想在运行时生成与一些预构建的 bean 容器相关的工厂代理,例如
public Object getFactoryBean(String name){
return beanContainer.get(name);
}
类似于
org.springframework.beans.factory.config.ServiceLocatorFactoryBean
但建立在 LambdaMetaFactory 之上。我尝试了以下代码,但出现异常
static <T> T getFactory(Class<T> factoryClass) {
T factory =null;
try {
final MethodHandles.Lookup lookup = MethodHandles.lookup();
Class<?> beanType = factoryClass.getMethod("get", String.class).getReturnType();
final CallSite site = LambdaMetafactory.metafactory(lookup,
"get",
MethodType.methodType(factoryClass, String.class),
MethodType.methodType(beanType),
lookup.findStatic(ReflectionUtil.class, "getFactoryBean", MethodType.methodType(Object.class, String.class)),
MethodType.methodType(beanType));
factory = (T) site.getTarget().invoke();
} catch(Throwable e) {
e.printStackTrace();
}
return factory;
}
public static Object getFactoryBean(String beanName) {
return beanMap.get(beanName);
}
java.lang.invoke.WrongMethodTypeException: cannot convert MethodHandle(String)Factory1 to ()Object
at java.lang.invoke.MethodHandle.asTypeUncached(MethodHandle.java:775)
at java.lang.invoke.MethodHandle.asType(MethodHandle.java:761)
at java.lang.invoke.Invokers.checkGenericType(Invokers.java:321)
提前致谢。