27

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?

pkaeding
  • 36,513
  • 30
  • 103
  • 141
dpaksp
  • 727
  • 3
  • 12
  • 24
  • 1
    Can you elaborate ? Its not so clear to understand. – Puru Jun 16 '10 at 05:47
  • 3
    I believe the term you're looking for is "reflection". – Stephen Jun 16 '10 at 05:47
  • and i'm also sure what he meant is this one: http://stackoverflow.com/questions/160970/how-do-i-invoke-a-java-method-when-given-the-method-name-as-a-string – gumuruh May 02 '12 at 07:54
  • Also see http://stackoverflow.com/questions/160970/how-do-i-invoke-a-java-method-when-given-the-method-name-as-a-string – Drew LeSueur Jan 18 '13 at 14:01
  • Yes, using reflection and dynamic method invocation you can do this. If you google "java dynamic method invocation" you'll get some interesting hits. Here is a [tutorial](http://www.developer.com/java/other/article.php/3606401/Dynamic-LoadingReloading-of-Classes-and-Dynamic-Method-Invocation-Part-1.htm). This implements a kind of plotting language like you are describing. – Peter Tillemans Jun 16 '10 at 05:51
  • @PeterTillemans ironically, i got here by searching "java dynamic method calling" as this SO question is the first result of that search :) – brett Feb 22 '17 at 13:03

2 Answers2

41

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 prefer methodName to method_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

craigcaulfield
  • 3,381
  • 10
  • 32
  • 40
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
25

It's possible using reflection, although you should probably question your design somewhat if you need that sort of behavior. Class.getMethod takes a String for the method name and returns a Method object, which you can then call .invoke on to call the method

These Javadoc pages should be helpful:

Sample code (assuming the yyyyyy methods take one int argument, just to show argument passing):

yyyyyy obj = new yyyyyy();
String[] methodNames = {"foo", "bar", "baz"};
for(String methodName : methodNames) {
    Method method = Class.forName("yyyyyy").getMethod(methodName, new Class[] {int.class});
    method.invoke(obj, 4); // 4 is the argument to pass to the method
}
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175