Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method with a string

Tags:

java

string

oop

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;?

like image 309
gmlyra Avatar asked Aug 17 '26 09:08

gmlyra


1 Answers

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
like image 180
pb2q Avatar answered Aug 18 '26 23:08

pb2q



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!