Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get a reference to a Java method to invoke it later?

Tags:

java

methods

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?

like image 925
Geo Avatar asked Jan 06 '10 21:01

Geo


2 Answers

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.

like image 77
OscarRyz Avatar answered Sep 30 '22 17:09

OscarRyz


Java 7 will have closures which will let you do this.

Until this is available you have two options

  • Hold a reference to an interface with a known method on and call that
  • Use reflection to call the method.
like image 24
Robert Christie Avatar answered Sep 30 '22 19:09

Robert Christie