How to get Method object in Java without using method string names
Java 8 method references would be ideal for this - the tricky part is getting to the underlying method, because the method reference syntax itself results in an opaque lambda object.
Found this after a bit of searching:
http://benjiweber.co.uk/blog/2013/12/28/typesafe-database-interaction-with-java-8/
Neat trick - call the method on a proxy object that records the method name. Haven't tried it but looks promising.
There is actually a library that can do this:
Jodd MethRef - Strongly-typed method name references
https://jodd.org/ref/methref.html
Methref<Str> m = Methref.on(Str.class); // create Methref tool
// example #1
m.to().boo();
m.ref(); // returns String: 'boo'
In your method call: Method me = (new MethodNameHelper(){}).getMethod();
/**
* Proper use of this class is
* Method me = (new MethodNameHelper(){}).getMethod();
* the anonymous class allows easy access to the method name of the enclosing scope.
*/
public class MethodNameHelper {
public Method getMethod() {
return this.getClass().getEnclosingMethod();
}
}