Explicit use of LambdaMetafactory

2020-02-08 04:58发布

I'm trying to explicitly use LambdaMetafactory.metafactory, I can't understand why it works only with the Runnable functional interface. For Example this code does what it is expected (it prints "hello world"):

public class MetafactoryTest {

    public static void main(String[] args) throws Throwable {

        MethodHandles.Lookup caller = MethodHandles.lookup();
        MethodType methodType = MethodType.methodType(void.class);
        MethodType invokedType = MethodType.methodType(Runnable.class);
        CallSite site = LambdaMetafactory.metafactory(caller, 
                                                      "run", 
                                                      invokedType, 
                                                      methodType, 
                                                      caller.findStatic(MetafactoryTest.class, "print", methodType), 
                                                      methodType);
        MethodHandle factory = site.getTarget();
        Runnable r = (Runnable) factory.invoke();
        r.run();
    }

    private static void print() {
        System.out.println("hello world"); 
    }    
}

The problem arise when I try to use a different functional interface, such as Supplier. The following code does not work:

public class MetafactoryTest {

    public static void main(String[] args) throws Throwable {

        MethodHandles.Lookup caller = MethodHandles.lookup();
        MethodType methodType = MethodType.methodType(String.class);
        MethodType invokedType = MethodType.methodType(Supplier.class);
        CallSite site = LambdaMetafactory.metafactory(caller, 
                                                      "get", 
                                                      invokedType, 
                                                      methodType, 
                                                      caller.findStatic(MetafactoryTest.class, "print", methodType), 
                                                      methodType);
        MethodHandle factory = site.getTarget();
        Supplier<String> r = (Supplier<String>) factory.invoke();
        System.out.println(r.get());        
    }
    private static String print() {
        return "hello world";
    }    
}


Exception in thread "main" java.lang.AbstractMethodError: metafactorytest.MetafactoryTest$$Lambda$1/258952499.get()Ljava/lang/Object;
    at metafactorytest.MetafactoryTest.main(MetafactoryTest.java:29)

Shouldn't the two snippet of code work in a similar way, which is the problem in the second snippet of code?

Moreover the following code, that should be equivalent, works well:

public class MetafactoryTest {

    public static void main(String[] args) throws Throwable {
        Supplier<String> r = (Supplier<String>) () -> print();
        System.out.println(r.get());        
    }

    private static String print() {
        return "hello world";
    }    
}

Edit

Another solution that avoids to change the method return type is to define a new functional interface:

public class MetafactoryTest {

    @FunctionalInterface
    public interface Test {
        String getString();
    }

    public static void main(String[] args) throws Throwable {

        MethodHandles.Lookup caller = MethodHandles.lookup();
        MethodType methodType = MethodType.methodType(String.class);
        MethodType invokedType = MethodType.methodType(Test.class);
        CallSite site = LambdaMetafactory.metafactory(caller, 
                                                      "getString", 
                                                      invokedType, 
                                                      methodType, 
                                                      caller.findStatic(MetafactoryTest.class, "print", methodType), 
                                                      methodType);
        MethodHandle factory = site.getTarget();
        Test r = (Test) factory.invoke();
        System.out.println(r.getString());        
    }

    private static String print() {
        return "hello world";
    }  

3条回答
爷的心禁止访问
2楼-- · 2020-02-08 05:16

I had a situation where I needed to call a function passing some parameter to it. Similar to @Sahil Gupta question. I managed to solve it using a BiFunction with some adjustments:

public void testFunctionWithParameter() throws Throwable {
    SimpleBean simpleBean = new SimpleBean();

    MethodHandles.Lookup caller = MethodHandles.lookup();
    MethodType invokedType = MethodType.methodType(BiFunction.class);
    MethodType biFunc = MethodType.methodType(String.class, String.class);
    MethodHandle target = caller.findVirtual(SimpleBean.class, "simpleFunction", biFunc);
    MethodType func = target.type();


    CallSite site = LambdaMetafactory.metafactory(
            caller,
            "apply",
            invokedType,
            func.generic(),
            target,
            MethodType.methodType(String.class, SimpleBean.class, String.class)
    );

    BiFunction<SimpleBean, String, String> fullFunction = (BiFunction<SimpleBean, String, String>) site.getTarget().invokeExact();


    System.out.println(fullFunction.apply(simpleBean, "FOO"));

}

private class SimpleBean {
    public String simpleFunction(String in) {
        return "The parameter was " + in;
    }
}

I hope it helps someone.

查看更多
淡お忘
3楼-- · 2020-02-08 05:18

This is another example with a more easy to understand variable names:

public class Demo {
    public static void main(String[] args) throws Throwable {
        Consumer<String> consumer = s -> System.out.println("CONSUMED: " + s + ".");

        consumer.accept("foo");

        MethodHandles.Lookup caller = MethodHandles.lookup();

        MethodType lambdaBodyMethodType = MethodType.methodType(void.class, String.class);
        MethodHandle lambdaBody = caller.findStatic(
                Demo.class, "my$lambda$main$0", lambdaBodyMethodType);

        // Because of the type erasure we must use Object here
        // instead of String (Consumer<String> -> Consumer).
        MethodType functionalInterfaceMethodType =
                MethodType.methodType(void.class, Object.class);

        // we must return consumer, no closure -> no additional parameters
        MethodType callSiteType = MethodType.methodType(Consumer.class);

        CallSite site = LambdaMetafactory.metafactory(
                // provided by invokedynamic:
                caller, "accept", callSiteType,
                // additional bootstrap method arguments:
                functionalInterfaceMethodType,
                lambdaBody,
                lambdaBodyMethodType);

        MethodHandle factory = site.getTarget();
        Consumer<String> r = (Consumer<String>) factory.invoke();

        r.accept("foo");
        r.accept("bar");
    }

    private static void my$lambda$main$0(String s) {
        System.out.println("CONSUMED: " + s + ".");
    }
}

Because LambdaMetafactory creates a synthetic factory class that then is used to create target interface, callSiteType has a type of this factory create() method. This create() method is called implicitly by invokedynamic - LambdaMetafactory returns a CallSite that has a method reference to the create method. For lambdas with closures you will call the factory like factory.create(capturedValue1, ..., capturedValueN) and so you must modify callSiteType accordingly.

查看更多
SAY GOODBYE
4楼-- · 2020-02-08 05:25

The difference between Runnable and Supplier is that Supplier uses a generic type.

At runtime Supplier doesn't have a String get() method, it has Object get(). But the method you implement returns a String. You need to distinguish between those 2 types. Like this:

public class MetafactoryTest {

    public static void main(String[] args) throws Throwable {

        MethodHandles.Lookup caller = MethodHandles.lookup();
        MethodType methodType = MethodType.methodType(Object.class);
        MethodType actualMethodType = MethodType.methodType(String.class);
        MethodType invokedType = MethodType.methodType(Supplier.class);
        CallSite site = LambdaMetafactory.metafactory(caller, 
                                                      "get", 
                                                      invokedType, 
                                                      methodType, 
                                                      caller.findStatic(MetafactoryTest.class, "print", actualMethodType), 
                                                      methodType);
        MethodHandle factory = site.getTarget();
        Supplier<String> r = (Supplier<String>) factory.invoke();
        System.out.println(r.get());
    }

    private static String print() {
        return "hello world";
    }    
}
查看更多
登录 后发表回答