Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Method object in Java without using method string names

Tags:

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

like image 709
Andrejs Avatar asked Mar 25 '12 21:03

Andrejs


People also ask

How do you find the method object?

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.

Can there be object without having any 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.

How do you access a method using an object?

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.


2 Answers

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.

like image 76
ddan Avatar answered Oct 12 '22 22:10

ddan


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();
  }
}
like image 21
Jim Avatar answered Oct 12 '22 22:10

Jim