nanogru
nanogru

Reputation: 33

Call Method based on String

Imagine that I have String X. How could I call method X() in java? An example implementation (this is not my application, as this question is more theoretical and does not have a specific application in mind):

I have a console line program. A scanner object is being used for input. We have 1000s of methods in our program, and we need users in our console to be able to execute these methods by name. For example (psuedocode),

public static void main(String[] args) {
   // string X is prompted to be either doBlah, getBlah, etc...
   String X = keyScanner.next();
   execute(X + "()"); //psuedocode for what I would like to do
}
public void doBlah() {}
public void getBlah() {}
public void letNooo() {}
// etc... (just random method names, no particular pattern)

How could I do this in Java, or really any language? Thank you.

Upvotes: 2

Views: 3848

Answers (1)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

You'll have to use reflection:

Method m = Main.class.getMethod("doBlah");
m.invoke(new Main(), null)

You can add many more other arguments both for retrieving the method and invoking it, all of which can be found here.

Upvotes: 1

Related Questions