Shortcut for obtaining a MethodHandle for an anonymous code fragment

Vladimir Ivanov vladimir.x.ivanov at oracle.com
Mon Jan 11 16:12:40 UTC 2021


> 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


More information about the mlvm-dev mailing list