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?
You can do it like that:
public static void main(String[] args) {
final String className = "com.my.package." + args[0];
try {
Class<?> clazz = Class.forName(className);
Method method = clazz.getMethod("say");
Object object = clazz.newInstance();
method.invoke(object);
} catch (ClassNotFoundException e) {
System.err.println("Error: No such class exists");
} catch (SecurityException e) {
System.err.println("Error: You are not allowed to do that");
} catch (NoSuchMethodException e) {
System.err.println("Error: No such method exists");
} catch (InstantiationException e) {
System.err.println("Error: Unable to instantiate");
} catch (IllegalAccessException e) {
System.err.println("Error: No access to class definition");
} catch (IllegalArgumentException e) {
System.err.println("Error: Illegal argument");
} catch (InvocationTargetException e) {
System.err.println("Error: Bad target");
}
}
Note: as your say() method is static, you can replace:
Object object = clazz.newInstance();
method.invoke(object);
by:
method.invoke(null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With