1

I am a very heavy user of Java reflection. I think we all agree the syntax is a tad less than user friendly but worst of all, you need to use strings all the time. Clearly this is error prone.

Since Java 8 we've got lambdas! They have a nice syntax to reference methods:

 interface A { String foo(); }

We can then refer to the foo method with A::foo.

 void inspect( Function<A,String> f) { }

 void test() {
      inspect(A::foo);
 }

Unfortunately, the compiler and the runtime seem to go out of their way to hide any reference to the underlying method A::foo. I'd first naively hoped that the MethodHandlesProxies class would be used to create the lambda but the isWrapperInstance method returns false so they use an internal mechanism.

Now although I realize that it would mean create functional interfaces for each invocation order, I still really like this syntax so much that I really want to use it.

I tried:

  • `MethodHandlesProxies.isWrapperInstance
  • `Lookup.revealDirect(..).reflectAs

Anybody any ideas how to find the underlying method that backs the lambda?

Peter Kriens
  • 15,196
  • 1
  • 37
  • 55
  • 2
    Hm, tricky one. Perhaps some of the comments in https://stackoverflow.com/questions/19845213/how-to-get-the-methodinfo-of-a-java-8-method-reference may be helpful. – Hulk Jul 09 '22 at 08:43
  • 1
    Is https://stackoverflow.com/questions/40850926/nameof-equivalent-in-java/46679366#46679366 an option? – Progman Jul 09 '22 at 09:20
  • 1
    "I am a very heavy user of Java reflection." - Umm yes. Reflection is like a drug. Once you get the habit it is hard to kick :-) – Stephen C Jul 09 '22 at 10:29
  • I avoid Reflection. It often bypasses the compiler's built-in checks, and makes stack traces more complicated. In many cases where I used to be tempted to use reflection, I can now uses lambdas and function pointers, but before java 8, I would use anonymous classes. – MiguelMunoz Jul 10 '22 at 19:51

1 Answers1

0

I strongly suspect there's no way to do this. From my investigations, it looks like lambdas and function pointers were not designed to work with reflection at all. They may be intended to be an alternative to reflection, which is how I've been using them.

MiguelMunoz
  • 4,548
  • 3
  • 34
  • 51
  • Strictly speaking, lambdas and function pointers are an alternative to writing a bunch of boiler-plate helper classes or anonymous classes. They are not as dynamic as reflection. – Stephen C Jul 09 '22 at 10:26