我正在解析一个正在映射到某些java代码的文本文件:
public void eval(Node arg)
{
if(arg.data.equals("rand"))
{
moveRandomly();
}
else if(arg.data.equals("home"))
{
goHome();
}
else if(arg.data.equals("iffood"))
{
ifFoodHere(arg.left, arg.right);
}//snip..
这需要重新评估一千次,而且我不必每次都要遍历整个事情。有没有办法进行一次遍历,然后让它成为每隔一次调用一次的函数?
答案 0 :(得分:3)
你可以制作一张Runnables地图:
Map<String, Runnable> methods = new HashMap<String, Runnable>();
methods.put("rand", new Runnable()
{
public void run()
{
moveRandomly();
}
});
...
然后在你的方法
public void eval(Node arg)
{
Runnable command = methods.get(arg.data);
command.run();
}
答案 1 :(得分:2)
创建一个匿名内部类。
类似的东西:
public Callable<Void> eval(Node arg)
{
if(arg.data.equals("rand"))
{
return new Callable<Void>{ public Void call() { moveRandomly(); return null; } };
}
...
}
Callable<Void> f = eval(a);
f.call();
答案 2 :(得分:1)
如果您知道所有可以预期的参数/命令,我可能会这样做:
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();
}
//...
}
你的eval()就变成了,简单地说:
try {
Args.eval(arg);
} catch (IllegalArgumentException e) {
// Handle unknown arg.data
}