0

Suppose I have a bunch of classes with methods, for example

class A {
   public void foo();
}

can a function be written in another class...

public String getMethodName(Function<?> func) { ... }

which when called with any method reference, for example

String val = getMethodName(A::foo);

would return the name of the method as a String, in this example "foo"?

Alex R
  • 11,364
  • 15
  • 100
  • 180
  • May I ask why if you wouldn't just use the [`getName`](https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Method.html#getName()) on `foo`? What is the context of this code? – GBlodgett Dec 13 '18 at 04:19
  • No. If you're looking to get the name of a method at runtime, you'll need to use reflection. – Jacob G. Dec 13 '18 at 04:19
  • You already know the method name, as you are passing it as a param! Why not just make a string of that name only???!!! – Ketan Dec 13 '18 at 04:20
  • 1
    @Ketan That approach has disadvantages (though it's the best you can do in Java). For instance, if you rename the `foo` method, the static type compilation will not complain if you forget to change the string. – yshavit Dec 13 '18 at 04:26
  • @yshavit thank you for understanding my requirement. I am looking to obtain a compile-time, static binding to the method name. – Alex R Dec 13 '18 at 04:59

1 Answers1

0

It is only possible thru bytecode decompilation because

foo(Baz::bar)

is syntactic sugar for

class SomeFakeName implement Interface {
   public void methodName() {
        Baz.bar();
   }
}

foo(new SomeFakeName())

I assume following declarations:

void foo(Interface p){}
interface Interface {
    void methodName();
}
talex
  • 17,973
  • 3
  • 29
  • 66