For Programmers: Free Programming Magazines  


Home > Archive > Java Help > April 2005 > Calling a method









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Calling a method
cdx

2005-04-21, 4:00 pm

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.

Any ideas on that?
Bryce

2005-04-21, 4:00 pm

On Thu, 21 Apr 2005 12:33:43 -0400, cdx <jm1@dicehome.com> 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
kaeli

2005-04-21, 4:00 pm

In article <Q8adnTn68-5TSPrfRVn-oQ@comcast.com>, jm1@dicehome.com enlightened
us with...
> 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.
>
> Any ideas on that?


You have to use reflection to do that sort of thing. There's nothing as
simple as just one line of code for it (like javascript and asp have), no.
Here are a couple options.
http://mindprod.com/jgloss/eval.html

--
--
~kaeli~
If a book about failures doesn't sell, is it a success?
http://www.ipwebdesign.net/wildAtHeart
http://www.ipwebdesign.net/kaelisSpace

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com