Is it possible to get a reference to a Java method to invoke it later?
java, methods
Solution
Yes, it is possible.
You just have the get the method and invoke it.
Here's some sample code:
$cat InvokeMethod.java
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
public class InvokeMethod {
public static void invokeMethod( Method m , Object o , Object ... args )
throws IllegalAccessException,
InvocationTargetException {
m.invoke( o, args );
}
public static void main( String [] args )
throws NoSuchMethodException,
IllegalAccessException,
InvocationTargetException {
SomeObject object = new SomeObject();
Method method = object.getClass().getDeclaredMethod( "someMethod", String.class );
invokeMethod( method, object, "World");
}
}
class SomeObject {
public void someMethod( String name ){
System.out.println( " Hello " + name );
}
}
$javac InvokeMethod.java
$java InvokeMethod
Hello World
$
Now the question is, what are you trying to do? perhaps are better ways. But as for your question the answer is YES.
Problem
Is it possible to obtain references to an object's methods? For example, I'd like to have a method that invokes other methods as callbacks. Something like: ``` public class Whatever { public void myMethod(Method m,Object args[]) { } } ``` Is this possible? EDIT: I meant an object's methods. I take it it's not possible?