Code Comments
Programming Forum and web based access to our favorite programming groups.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?
Post Follow-up to this messageOn 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
Post Follow-up to this messageIn article <Q8adnTn68-5TSPrfRVn-oQ@comcast.com>, jm1@dicehome.com enlightene
d
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
Post Follow-up to this message
Show a Printable Version
Email This Page to Someone!
Receive updates to this thread
Powered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.