【发布时间】: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