0

I'm new to Java and I want to execute a method corresponding to a String I receive. In Python I would just do this

myString = "create"
options = {
    "create": self.create,
    "delete": self.delete,
    "list_jobs": self.list_jobs
}
options[myString]()

Is this possible in Java?

2 Answers2

0

Java doesn't have anything like that, but you can use a switch.

switch (myString) {

    case "create":
        self.create;
        break;
    case "delete":
        self.delete;
        break;
    case "list_jobs":
        self.list_jobs;
        break;
}

Note that you probably should use more complicated object oriented concepts, but for simple programs this works fine.

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
0

I would use a Map<String, Runnable>.

Map<String, Runnable> commandTable = new HashMap<String, Runnable>();

static void initCommandTable() {
    commandTable.add("foo", new Runnable() { 
        @Override
        public void run() {
             //implement foo command
             ...
        });

    commandTable.add("bar", new Runnable() { 
        @Override
        public void run() {
             //implement bar command
             ...
        });

    ...
}

void doCommand(String command) {
    commandTable.get(command).run();
}

Yeah, Java is a lot more verbose than Python. But we knew that already.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57