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
MethodHandleto a functionalinterfaceimplementation using the same feature, Java 8’s lambda expressions and method references use.It’s all about calling
LambdaMetafactory.metafactorywith the method handle, the desired interface and the name of the soleabstractmethod 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
samMethodTyperefers the the method type of the rawinterface’s functional signature, so for the raw typeFunctionwe must implementObject apply(Object)while theinstantiatedMethodTypedescribes the methodInteger apply(String). That’s why the method.generic()is called on the methodType for the fourth parameter which will convert(String)Integerto(Object)Object.This is even trickier for constructors as the constructor will be looked up with a
(String)voidtype while the functional type is the same as in thestaticmethod case. So for astaticmethod the method’sMethodTypematches theMethodTypewhile for a constructor we have to use a different type for the lookup:But that’s only for completeness, for the type
Integeryou shouldn’t call the constructor but usevalueOfmethod, preferably.