【问题标题】:passing parameters through hashmap to function in java通过hashmap传递参数以在java中运行
【发布时间】:2015-12-15 22:39:20
【问题描述】:

我试图在 java 中构建一个类似的命令行工具,例如,如果我在控制台中写下“dir c:/....”,它将激活我的 Dir 类并获得“c:/ ...." 路径作为 Dir 类的参数,并使用 hashmap 这样做。

我不知道如何通过命令行和 hashmap 传递参数, 有可能吗?

每个命令都有它自己的类,它实现了主要的“Command”接口,带有一个 doCommand() 函数。

在 CLI 类中运行 start() 函数后,它应该接受命令并执行请求的命令。

命令界面:

public interface Command {
   public void doCommand();
}

我的 CLI 类:

public class CLI {

BufferedReader in;
PrintWriter out;

HashMap<String, Command> hashMap;
Controller controller;

public CLI(Controller controller, BufferedReader in, PrintWriter out,
        HashMap<String, Command> hashMap) {
    this.in = in;
    this.out = out;
    this.hashMap = hashMap;
}

public void start() {

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                out.println("Enter a command please:");
                String string = in.readLine();
                while (!string.equals("exit")) {
                    Command command = hashMap.get(string);
                    command.doCommand();

                    string = in.readLine();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }).start();
}
}

让我们以我的 DirCommmand 为例,正如我之前所说,它应该通过我的 hashMap 配置识别“dir”字符串,并且应该将下一个单词作为路径的字符串参数传递

public class DirCommand implements Command {

@Override
public void doCommand() {
    System.out.println("doing dir command...");

}

}

还有我的 hashmap 配置:

    hashMap.put("dir", new DirCommand());

在不同的类中设置 hashMap 配置,并在项目开始时将其传递给 CLI 类的 hashMap 对象。

我很想得到一些帮助,因为我不知道该怎么做。

【问题讨论】:

  • 您为什么两次列出您的CLI 课程?
  • 你是对的,我错误地添加了两次。我修复了 Dir 类

标签: java


【解决方案1】:

首先,为了将参数传递给doCommand,我要做的是使用可变参数列表,例如:

public interface Command {
    public void doCommand(String... params);
}

其次,我会将空格上的输入字符串拆分为:

String[] result = command.split(" ");

最后,命令将是 result[0],其余的将传递给 doCommand 方法。

【讨论】:

  • 我已经想到了,但我认为这个问题会有一个更简单的解决方案,也许是哈希映射对象中的内置解决方案。谢谢你的回答,但我会等待也许有一个更简单的解决方案然后这个:)
  • 在您当前的设计中,我敢打赌这是更简单的解决方案。我建议你看看 Command 设计模式。那里有很多实现。也许它们更复杂,但也更健壮,具体取决于您的问题。
猜你喜欢
  • 1970-01-01
  • 2012-03-15
  • 2017-08-14
  • 2020-09-08
  • 2017-03-24
  • 1970-01-01
  • 2015-01-15
  • 2017-09-25
相关资源
最近更新 更多