I have a String array that contains names of method in the yyyyyy
class
In the xxxxxx
class I'm making a yyyyyy
instance (say obj
). Now I can call obj.function_name()
, except I want to read function_name
from the String array in a loop. Is this possible?
You can, using reflection. It is done by calling
Yyyy.class.getMethod("methodName").invoke(someArgs)
You'd have to handle a bunch of exceptions, and your method must be
public
. Note that java coding conventions prefermethodName
tomethod_name
.Using reflection, however, should be a last resort. You should be using more object-oriented techniques.
If you constantly need similar features, perhaps you can look at some dynamic language running on the java platform, like groovy
It's possible using reflection, although you should probably question your design somewhat if you need that sort of behavior.
Class.getMethod
takes aString
for the method name and returns aMethod
object, which you can then call.invoke
on to call the methodThese Javadoc pages should be helpful:
Class.getMethod
Method.invoke
Sample code (assuming the
yyyyyy
methods take oneint
argument, just to show argument passing):