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?

1
  • 3
    There are no functions in Java. The closest you'd get is static methods. Regardless, you should read about reflection - that's more or less what you're looking for. Commented Dec 9, 2017 at 21:24

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Closest. I'll have to abandon that train of thought though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.