Re: Calling a method



On Thu, 21 Apr 2005 12:33:43 -0400, cdx <jm1@xxxxxxxxxxxx> wrote:

>Here's another thing I'm trying to do that I hope someone can help with.
> I'd like to call a method on an instance of a class using a string as
>the method name. Something like anInstance.perform("getName"), which
>would call the method getName() on the instance and return the value
>from that.

The following is the same as calling:
String testString = "Testing 123";
int result = testString.indexOf("123");


String testString = "Testing 123";
Class clazz = String.class;
Class[] parameterTypes = {String.class};

Method method = clazz.getDeclaredMethod("indexOf",
parameterTypes);
Object[] parameters = {"123"};
Object result = method.invoke(testString, parameters);

System.out.println(result.toString()); // 8

--
now with more cowbell
.