PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How to indirectly run a method reference in Java 8?

 November 04, 2022     java, java-8, lambda     No comments   

Issue

The general questions are:

  • When using the syntax object::aMethod, can it be converted to a type such as MethodHandle as a functional interface?
  • If no, how can a method reference be indirectly invoked in Java 8 if at all possible?

As an example, imagine we'd like to have a MethodRefRunner as:

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

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

In the above snippet, one option for WHATTYPE is java.util.function.Function but very restrictive. As this answer mentions, prior to version b75, there was a java.util.function.Block was available and might be handy.

On the other side, any chance that WHATTYPE could be in some way converted to a java.lang.invoke.MethodHandle?

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


Solution

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.)



Answered By - Maurice Naftalin
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing