如果你知道你可以期望的所有论点/建议,那么,我可以这样做:
enum Args {
home, rand, iffood;
private Method method;
private Args () {
try {
this.method = Commands.class.getMethod(this.name(), Node.class);
} catch (final Exception e) {}
}
public void invoke (final Node args)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
this.method.invoke(null, args);
}
public static Args valueOf (final Node arg) {
return valueOf(arg.data);
}
public static void eval (final Node arg)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
valueOf(arg).invoke(arg);
}
}
执行指挥:
class Commands {
public static void home (final Node arg) {
goHome(); // Call the implementation
// or simply make these bodies the implementations.
}
public static void iffood (final Node arg) {
ifFoodHere(arg.left, arg.right);
}
public static void rand (final Node arg) {
moveRandom();
}
//...
}
之后,你就变成了:
try {
Args.eval(arg);
} catch (IllegalArgumentException e) {
// Handle unknown arg.data
}