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.

3
  • Reflection API could help you :) Commented May 2, 2016 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? Commented May 2, 2016 at 12:42
  • That would not call method func(). That would just println func(); Commented May 2, 2016 at 12:42

1 Answer 1

1
Method m = YourClass.class.getMethod("methodName", parametersOfYourMethods);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.