How to indirectly launch a method reference in Java 8?

General issues:

  • Using the syntax object::aMethod can it be converted to a type, such as MethodHandle , as a functional interface?
  • If not, how can you indirectly call a method reference in Java 8?

As an example, suppose we would like to have a MethodRefRunner like:

 class MethodRefRunner { static void execute(Object target, WHATTYPE mref, Object... args) { mref.apply(args); } } 

And it can be used like: MethodRefRunner.execute(o, o::someMethod, someParam)

In the above snippet, one parameter for WHATTYPE is java.util.function.Function , but very restrictive. As stated in this answer , prior to version b75, java.util.function.Block existed, and this can be convenient.

On the other hand, is there any chance that WHATTYPE could be somehow converted to java.lang.invoke.MethodHandle ?

Note to Java experts: Refine the title of the questions as needed.

+8
java lambda java-8
Jun 17 '13 at 8:16
source share
2 answers

I don’t think there is any way to do what you want. WHATTYPE should be a functional interface, not necessarily Function , but one with a single abstract method corresponding to somemethod . This is a common interface type, subject to the usual rules that define Java types. java.util.function.Block was an ordinary interface type like this, and was not special in what you seem to think. (He's still around, by the way, now called Consumer .)

+8
Jun 17 '13 at 11:25
source share

A method reference works just like a lambda, and like a lambda, it does not have a β€œtype” of its own. Its type depends on the context in which it is used. Therefore, your question does not make sense. If you use a method reference in a call to this MethodRefRunner.execute() method, then the type of the method reference will be an instance of WHATTYPE (whatever it is), because this is what the method was declared for acceptance. If you got it from somewhere else, well, this place will know what type it is.

+5
Jun 17 '13 at 23:40
source share



All Articles