I'm looking for a convenient workaround for getting the Method object from a method. The idea:
Method fooMethod = getMethod( new MyObject().foo() ) // returns method "foo" in MyObject
The obvious way is to use the name of the method as a string:
Method fooMethod = MyObject.class.getMethod("foo")
but I want to avoid this because if I rename foo() that code will stop working or I have rename the string in all the places where it is used.
The use case is that I want to use something similar to ProperyChangeListeners however those rely on the method name as string. I'd like to use the actual method (safely) and not rely on strings.
What could I use to get the method in a rename safe way?
UPDATE: I'd like to find a pure java solution that does not rely on IDE features
getMethod() returns a Method object that reflects the specified public member method of the class or interface represented by this Class object. The name parameter is a String specifying the simple name of the desired method.
4 Answers. Show activity on this post. Raman is right in that all objects inherit the methods of the Object class, so you technically can't have a class without any methods at all.
You also use an object reference to invoke an object's method. You append the method's simple name to the object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With