I want to map a String into a Java class. For example, I want to define my Main class such that it works in the following way:
$ java Main SayHello
Hello!
$ java Main SayBye
Bye!
$ java Main SayHola
Error: No such class exists
Here is the code.
public class Main {
public static void main(String[] args) {
// Call args[0].say()
}
}
public class SayHello {
public static void say() {
System.out.println("Hello!");
}
}
public class SayBye {
public static void say() {
System.out.println("Bye!");
}
}
I know that I could do it by manually mapping each possible value of args[0]
to a Java class, for example:
if (args[0].equals("SayHello")) {
SayHello.say();
}
But is there a way to do this automatically?