1

I want to call a method whose name (with or without parentheses and parameters) is stored in a string variable and call this method using this variable.

Until now I have found that in Java if you do this:

String str = "func();";
System.out.println(str);

This would call method func(). But I don't think this is recommended. So, my question is:

  1. Is it okay to do this?

  2. Is there any other way to do this?

Thanks.

Kian
  • 1,291
  • 1
  • 12
  • 23
user1934948
  • 175
  • 1
  • 3
  • 12
  • Reflection API could help you :) – z21 May 02 '16 at 12:41
  • Your example will simply print out a String that says `func();`. There's no method name `func()` being called. It's possible to to achieve that with reflection, but almost always there's a cleaner way to do it. Why do you think you need to invoke methods inside Strings? – Kayaman May 02 '16 at 12:42
  • That would not call method `func()`. That would just println func(); – Clark Kent May 02 '16 at 12:42

1 Answers1

1
Method m = YourClass.class.getMethod("methodName", parametersOfYourMethods);
suulisin
  • 1,320
  • 1
  • 9
  • 16