Java 如何为具有可变参数的方法构造MethodType
我未能为Java中的方法查找创建MethodType。下面是我的代码。在这段代码中,我想为sample::gwd方法创建一个MethodType,然后通过lookup().findStatic检索对此函数的引用。很明显,我无法获得方法引用,因为MethodType构造错误Java 如何为具有可变参数的方法构造MethodType,java,dynamic-invoke,dependent-method-type,Java,Dynamic Invoke,Dependent Method Type,我未能为Java中的方法查找创建MethodType。下面是我的代码。在这段代码中,我想为sample::gwd方法创建一个MethodType,然后通过lookup().findStatic检索对此函数的引用。很明显,我无法获得方法引用,因为MethodType构造错误 //I want to construct MethodType for Sample:gwd method, but do not know how to handle array parameters for 'gwd'
//I want to construct MethodType for Sample:gwd method, but do not know how to handle array parameters for 'gwd' method
MethodType mt = MethodType.methodType(Object.class, MethodHandle.class, MethodHandle.class, MethodHandle.class);
MethodHandle myMH = MethodHandles.lookup().findStatic(Sample.Class, "gwd", mt);
public class Sample
{
public static Object gwd(MethodHandle methodhandle, MethodHandle methodhandle1, MethodHandle methodhandle2, Object aobj[])
throws Throwable
{ .......... }
}
任何人都能帮上忙吗?谢谢您非常接近,您传递给
MethodHandles\lookup
的MethodType
缺少最后一个参数,对象数组
。这就是您需要的:
MethodType mt = MethodType.methodType(Object.class, MethodHandle.class, MethodHandle.class, MethodHandle.class, Object[].class);
顺便说一句,如果gwd
使用varargs而不是最终数组,这也是您需要的