How to construct a MethodType for a method with variant parameters

383 views Asked by At

I failed to create a MethodType for a method lookup in Java. Below is my code. In this code, I want to create a MethodType for the sample::gwd method, and then retrieval reference to this function by lookup().findStatic. It is clearly that i can not get the method reference because the MethodType is wrong constructed.

//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
    {  ..........   }
}

Anyone can help it? Thanks

1

There are 1 answers

0
Morgen On BEST ANSWER

You are very close, the MethodType you are passing to MethodHandles#lookup is missing the last parameter, the array of Objects. This is what you need:

MethodType mt = MethodType.methodType(Object.class, MethodHandle.class, MethodHandle.class, MethodHandle.class, Object[].class);

Incidentally, this is also what you would need if gwd used varargs instead of the final array.