2

Can Java do something like this ?:

String methodName = "multiply";

MyMath myMath = new MyMath();

/* "methodName" is expanded before being called */
int answer = myMath.methodName(2, 3);    

System.out.println(answer);

6

Is this type of feature / concept in a programming language known as "dynamic expansion", "variable interpolation", eval() (e.g. in various scripting languages), reflection, introspection, Java beans?

mvanle
  • 1,847
  • 23
  • 19
  • as far as I know, you can't. Why do you need it? – c-an Feb 08 '20 at 11:37
  • @c-an - Well, I am trying to put a method name in a properties file eg. "methodName = multiply" and then call it in the program without having to hardcode it or use `switch` or `if ... else if` or factory design patterns. – mvanle Feb 08 '20 at 11:48
  • I guess in this case, you need to use params and implement that you want to achieve. – c-an Feb 08 '20 at 12:05
  • It feels like a [Strategy Pattern](https://en.wikipedia.org/wiki/Strategy_pattern) – Karol Dowbecki Feb 08 '20 at 12:32

2 Answers2

5

Java doesn't provide this behaviour as a standard language feature, however it can be achieved with the Reflection API:

MyMath myMath = new MyMath();
String methodName = "multiply";
Method m = MyMath.class.getMethod(methodName);
m.invoke(myMath, 2, 3);
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • It is same as calling the function and telling what to do based on condition. – Kaushik Burkule Feb 08 '20 at 11:43
  • That being said, please note that the need for using reflection often indicates a bad design/architecture. So if possible, think about refactoring your code first. – Zabuzard Feb 08 '20 at 12:03
2

Yes, this is possible Reflection, however the performance is poor (confirmed in Java Reflection Performance).

Instructions about Reflection: https://www.oracle.com/technical-resources/articles/java/javareflection.html

This article describes how to use reflection. For you, the section "Invoking Methods by Name" would be the most interesting, but I recommend to read the whole article.

Stefan
  • 1,789
  • 1
  • 11
  • 16
  • *"however the performce is poor"* Citation? – T.J. Crowder Feb 08 '20 at 11:41
  • 1
    That comes from my personal experience. A quick search leaded me to this confirmation: https://stackoverflow.com/questions/435553/java-reflection-performance. Of course Oracle does not tell you the bad aspects of their Product. – Stefan Feb 08 '20 at 11:48
  • I would not say that anyone, including Oracle, tries to intentionally hide this fact. It is not that fast due to how it is implemented. It is more a technical limitation right now. And there are efforts to change that with newer versions. – Zabuzard Feb 08 '20 at 12:02