2

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.

3
  • 1
    You're looking for the reflection API. Commented Apr 30, 2014 at 0:26
  • Search for "reflection" in Java, also for "invoke()" Commented Apr 30, 2014 at 0:26
  • Are your methods declared in your class or maybe some of them are inherited? Are they all public? Also what about methods parameters? Commented Apr 30, 2014 at 0:28

1 Answer 1

1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.