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?
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.
Java 7 will have closures which will let you do this.
Until this is available you have two options
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