How to indirectly run a method reference in Java 8?

前端 未结 2 1112
别那么骄傲
别那么骄傲 2020-12-10 14:20

The general questions are:

  • When using the syntax object::aMethod, can it be converted to a type such as MethodHandle as a functional
相关标签:
2条回答
  • 2020-12-10 14:23

    A method reference works just like a lambda, and like a lambda, it doesn't have a "type" on its own. Its type depends on the context where it is used. So your question doesn't really make sense. If you use the method reference in a call to this MethodRefRunner.execute() method, then the type of the method reference will be an instance of WHATTYPE (whatever that is), because that's what the method was declared to accept. If you got it from somewhere else, well, that place will know what type it is.

    0 讨论(0)
  • 2020-12-10 14:29

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

    0 讨论(0)
提交回复
热议问题