MethodType methodType = MethodType.methodType(void.class, ByteBuffer.class);
MethodHandle handle = MethodHandles.publicLookup().findConstructor(type, methodType);
Function<ByteBuffer, Object> = handle; // ???
Is it possible to get the last assignment work? The inverted way does not work: Is it possible to convert method reference to MethodHandle?
Here another and copy-pastable example:
new Integer("123");
MethodType methodType = MethodType.methodType(void.class, String.class);
MethodHandle handle = MethodHandles.publicLookup().findConstructor(Integer.class, methodType);
Function<String, Integer> function1 = Integer::new;
Function<String, Integer> function2 = handle.toLambda(); // ???
«This answer» contains a code example showing how to convert a
MethodHandle
to a functionalinterface
implementation using the same feature, Java 8’s lambda expressions and method references use.It’s all about calling
LambdaMetafactory.metafactory
with the method handle, the desired interface and the name of the soleabstract
method and required signature.Both, the method’s documentation and it’s class documentation are very detailled.
So, for your request, example code may look like this:
You have to care about the signature types here. The fourth parameter
samMethodType
refers the the method type of the rawinterface
’s functional signature, so for the raw typeFunction
we must implementObject apply(Object)
while theinstantiatedMethodType
describes the methodInteger apply(String)
. That’s why the method.generic()
is called on the methodType for the fourth parameter which will convert(String)Integer
to(Object)Object
.This is even trickier for constructors as the constructor will be looked up with a
(String)void
type while the functional type is the same as in thestatic
method case. So for astatic
method the method’sMethodType
matches theMethodType
while for a constructor we have to use a different type for the lookup:But that’s only for completeness, for the type
Integer
you shouldn’t call the constructor but usevalueOf
method, preferably.