Java access bean methods with LambdaMetafactory

前端 未结 1 1753
慢半拍i
慢半拍i 2020-11-28 09:16

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

相关标签:
1条回答
  • 2020-11-28 09:40

    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));
    
    0 讨论(0)
提交回复
热议问题