2

Say I define such a function:

function helloWorld(e) {
  console.log("Hello " + e);
  return;
}

How Can i be able to call it like this:

String funcName="helloWorld"; 
funcName(e);

In Java is there a style as simple as in Javascript?

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
Dudus
  • 25
  • 8
  • 3
    There are no functions in Java. The closest you'd get is static methods. Regardless, you should read about [reflection](https://docs.oracle.com/javase/tutorial/reflect/) - that's more or less what you're looking for. – Mureinik Dec 09 '17 at 21:24

1 Answers1

2

This is known as Reflection:

import java.lang.reflect.Method;

public class Demo {

  public static void main(String[] args) throws Exception{
      Class[] parameterTypes = new Class[1];
      parameterTypes[0] = String.class;
      Method method1 = Demo.class.getMethod("method1", parameterTypes);

      Demo demo = new Demo();

      Object[] parameters = new Object[1];
      parameters[0] = "message";
      method1.invoke(demo , parameters);
  }

  public void method1(String message) {
      System.out.println(message);
  }

}

Taken from https://stackoverflow.com/a/4685609/5281806

Gonzalo Matheu
  • 8,984
  • 5
  • 35
  • 58
redMist
  • 219
  • 2
  • 12