dcsimg
call a method by extracting the method name from a String
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Friday, May 23, 2003 01:34 PM

How can I call a method by extracting the method's name from a String ?

I would like to extract from a String my method's name and then call it.
(I hope to have been clear enought..)




Thankyou
Andrea Franceschini
atari@libero.it

Re: call a method by extracting the method name from a String

Posted By:   Bahman_Barzideh  
Posted On:   Friday, May 23, 2003 03:05 PM

you can use reflections to do this. Try the following:

java.lang.reflect.Method method = MyClass.class.getDeclaredMethod ("foo", null);
method.invoke (instance, null);


where MyClass is the class whose method is to be invoked,
"foo" is the method to be invoked (in you case, the value
you extract from your String variable), and instance is the
instance of MyClass whose "foo" is to be
invoked.



The above example assumes the foo () method has no
arguments. If your method has arguments, then you would need to
create and pass the proper parameters instead of null in both lines of
code above.



By the way, you may also want to take a look at the java.lang.reflect.Constructor class. You can use this class along with getConstructor () method of Class to find any of the constructors of a class. This is useful when you need
to create an instance of a class by invoking one of its non-defualt constructors through reflections.
About | Sitemap | Contact