How to call a method with a string

java, oop, string

Solution

You'll need to use java `Reflection` to do this.

See: Class.getMethod()

Using your specific example:

String text = "Test";
Kyle k = new Kyle();
Class clas = k.getClass();

// you'll need to handle exceptions from these methods, or throw them:
Method method = clas.getMethod(text, null);
method.invoke(k, null);

That's without the exception handling required for `getMethod()` and `Method.invoke()`, and only covers the case of calling methods that take no arguments.

See also:

- Method doc

- Class doc

- This reflection article with examples

Problem

I am trying to use a string to call a method? Suppose I have a class called `Kyle` which has 3 methods: ``` public void Test(); public void Ronaldo(); public void MakeThis(); ``` And I have a string with the name of the method which I need to call: ``` String text = "Test()"; ``` Now I need to call the method whose name is inside of this string: ``` Kyle k = new Kyle(); ``` `k.text;`?

Original source