my question is strongly related to Explicit use of LambdaMetafactory in that thread, some very good examples are provided to use the LambdaMetafactory to access a static me
If you want to bind values to your lamba, you have to include these parameters to the invokedtype signature:
SimpleBean simpleBeanInstance = new SimpleBean();
MethodHandles.Lookup caller = MethodHandles.lookup();
MethodType getter=MethodType.methodType(Object.class);
MethodHandle target=caller.findVirtual(SimpleBean.class, "getObj", getter);
CallSite site = LambdaMetafactory.metafactory(caller,
"get", // include types of the values to bind:
MethodType.methodType(Supplier.class, SimpleBean.class),
getter, target, getter);
MethodHandle factory = site.getTarget();
factory = factory.bindTo(simpleBeanInstance);
Supplier r = (Supplier) factory.invoke();
assertEquals( "myCustomObject", r.get());
Instead of binding a value you may use a Function
which takes the bean as argument:
SimpleBean simpleBeanInstance = new SimpleBean();
MethodHandles.Lookup caller = MethodHandles.lookup();
MethodType getter=MethodType.methodType(Object.class);
MethodHandle target=caller.findVirtual(SimpleBean.class, "getObj", getter);
MethodType func=target.type();
CallSite site = LambdaMetafactory.metafactory(caller,
"apply",
MethodType.methodType(Function.class),
func.erase(), target, func);
MethodHandle factory = site.getTarget();
Function r = (Function)factory.invoke();
assertEquals( "myCustomObject", r.apply(simpleBeanInstance));