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:
Is it okay to do this?
Is there any other way to do this?
Thanks.
func();
. There's no method namefunc()
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?func()
. That would just println func();