Java 8 Map <string,runnable =“”>控制流

时间:2016-12-22 21:15:03

标签: java java-8 runnable

我试图熟悉一些新的Java 8功能(ha),但我遇到了一些控制流故障。

在下面的代码中,我有一个Map<String, Runnable>,所以我可以根据他们的名字调用方法,但我似乎无法弄清楚如何做两件事:

  1. 如何让这些方法获取参数?即我在地图中需要的语法是什么?#34; put&#34; s。
  2. 当我从&#34; get&#34;中调用这些方法时&#34; Dispatch中的方法,我无法返回方法的返回值(Status)。我怀疑这与调用方法的位置有关,但我无法弄明白。 Status只是一个枚举,toList方法只占用一个空格分隔的字符串并返回一个列表(这意味着用作REPL)。
  3. 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;
        }
    }
    

3 个答案:

答案 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>