Is it true that there is no shortcut for obtaining a method handle for
some code fragment?

That is, there is no way to write something like this?

   MethodHandle repeatIt = (String x) -> x + x;

Instead it's necessary to give the expression a name and put it into a
static method somewhere, and obtain a MethodHandle for it using
MethodHandles.lookup().

There's no language support for that, but you can write a utility method to convert a lambda into a method handle:

    wrapRunnable(() -> System.out.println(""));

    static MethodHandle wrapRunnable(Runnable r)  {
        return RUNNABLE_RUN.bindTo(r);
    }

    static final MethodHandle RUNNABLE_RUN;
    static {
        try {
RUNNABLE_RUN = MethodHandles.lookup().findVirtual(Runnable.class, "run", MethodType.methodType(void.class));
        } catch (NoSuchMethodException | IllegalAccessException e) {
            throw new InternalError(e);
        }
    }

Or even a generic version:

    wrap(Runnable.class, () -> System.out.println(""));

    static <T> MethodHandle wrap(Class<T> functionalInterface, T lambda) {
        MethodHandle sam = ... // find SAM in a functional interface
        return sam.bindTo(lambda);
    }

Best regards,
Vladimir Ivanov
_______________________________________________
mlvm-dev mailing list
mlvm-dev@openjdk.java.net
https://mail.openjdk.java.net/mailman/listinfo/mlvm-dev

Reply via email to