Thursday, April 3, 2008

how to invoke a method wihout knowing its method name? Dynamic Method Invocation

A new methodology - Dynamic Method Invocation

If you have a Method descriptor, you can invoke that method on any object of a class that contains it. Just call the Method's invoke() method passing the object (you can pass null if you're invoking a static method), and the argument list packed as an array of Object. Assume you are given class X containing this method:

 
public void work(int i, String s) {
            System.out.printf("Called: i=%d, s=%s%n", i, s);
}

To find and invoke this method dynamically, given an instance of it called "x", all you need to do is:

 
            Class clX = x.getClass();
 
            // To find a method, need array of matching Class types.
            Class[] argTypes = { int.class, String.class };
 
            // Find a Method object for the given method.
            Method worker = clX.getMethod("work", argTypes);
 
            // To invoke the method, need the invocation
            // arguments, as an Object array.
            Object[] theData = { 42, "Chocolate Chips" };
 
            // The last step: invoke the method.
            worker.invoke(x, theData);

By itself this is a bit tedious to code, but it is background for the next few sections.

No comments:

Post a Comment