我试图熟悉一些新的Java 8功能(ha),但我遇到了一些控制流故障。
在下面的代码中,我有一个Map<String, Runnable>
,所以我可以根据他们的名字调用方法,但我似乎无法弄清楚如何做两件事:
import java.util.*;
public class Dispatcher {
private Map<String, Runnable> func;
private Status status;
private List<String> command;
Optional<List<String>> opt;
public Dispatcher() {
func = new HashMap<>();
func.put("Method1", this::Method1);
func.put("Method2", this::Method2);
func.put("Help", this::Help);
status = Status.DONE;
}
private Status Help() {
return Status.DONE;
}
private Status Method1() {
return Status.DONE;
}
private Status Method2() {
return Status.DONE;
}
/**
* Execute the given command on a new process.
* @param command the full command requested by the caller including command name and arguments.
* @return The status of the requested operation.
*/
public Status Dispatch(String command) {
opt = CommandInterpreter.toList(command);
opt.orElse(new LinkedList<String>(){{add("Help");}});
func.get(opt.get().get(0));
return Status.DONE;
}
}
答案 0 :(得分:3)
如果您希望方法采用参数,那么您不希望将其存储为Runnable
。您可能需要Consumer
或其他接受参数的自定义功能接口 - 如果您想要返回值,请使用Function
或创建自己的界面。
答案 1 :(得分:3)
这是一个框架,您可以开始处理带有零个或多个参数的命令并返回状态代码。这只是一个蓝图,一个例子。也许它可以帮助你入门:
public class Dispatcher {
public static final int SUCCESS = 0;
public static final int FAILURE = 1;
public static final Command HELP = (args) -> {
String command = args[0];
System.out.println("Usage of " + command + ": bla bla");
return FAILURE;
};
public static final Command RENAME = (args) -> {
File oldName = new File(args[1]);
File newName = new File(args[2]);
return oldName.renameTo(newName) ? SUCCESS : FAILURE;
};
public final Map<String, Command> commands = new HashMap<String, Command>() {{
put("help", HELP);
put("rename", RENAME);
}};
public int dispatch(String commandLine) {
String[] args = commandLine.split("\\s");
return Optional.ofNullable(commands.get(args[0]))
.orElse(HELP)
.execute(args);
}
}
interface Command {
int execute(String... args);
}
答案 2 :(得分:1)
Runnable
界面不接受任何参数或具有返回类型。要添加返回类型,您可以使用Supplier<Status>
。要添加参数,请使用Function<ParamType, Status>
。