Java - 如何实现应用程序控制台解析器

时间:2015-06-18 00:54:29

标签: java command-line console-application command-line-interface command-line-arguments

所以我试图编写一个具有程序内控制台界面的应用程序(即你不必每次都用不同的命令从控制台运行程序),我想有一个解析器对象,用于解析来自用户的命令/选项。结构与此类似 -

ArrayList<String> example = new ArrayList<>(); 

/* PARSING */
ConsoleParser parser = new ConsoleParser();

Scanner input = new Scanner(System.in);
String parserArgs = input.nextLine(); 

while (parserArgs != "quit") 
{
     execute(parser.parse(parserArgs));
     parserArgs = input.nextLine();
}

所以我的想法是拥有一个控制台(在应用程序中),我可以输入命令,例如&#39;添加x&#39;或者&#39;包含x&#39;然后将其分配给&#39; parserArgs。&#39;然后命令字符串将被传递到ConsoleParser,在那里它将被解析并搜索有效命令。如果命令有效(并且具有必要的选项/参数),则ConsoleParser的parse()方法将以某种方式将方法(或方法名称)返回给main,以及方法需要的任何参数。所以,如果我想添加字符串&#34; foo&#34;到我的ArrayList,然后在控制台我可以键入&#39;添加foo&#39;然后将传递给解析器,然后解析器将返回main某些指令,需要调用ArrayList的add()方法&#39;例如&#39;有了#foo的论点。&#39;我知道这可以通过arraylist轻松完成,但我只是为了简单起见而在这里使用它。

1 个答案:

答案 0 :(得分:2)

根据您的问题,我不确定您是想要一个简单的解决方案还是一个优雅的解决方案。 这是一个优雅的解决方案看起来如何的草图。

您定义了一个功能接口,即只有一种方法的接口,由您的Parser返回。

像:

// I the Input type
// R the result type
public interface Fn<I,R> {

  R apply (I input);
}

第二个输入只提供执行方法

public interface Cmd<R> {

  R execute ();
}  

您可以定义控制台命令

public class CliCommand<A> {
  // constructor 
  public CliCommand(final String name, final Fn<String, A> parseFunct) 
  {
           // TODO
  }
} 

   // the parse function 
  public A parse(String arg) throws CliParseException {
      // TODO
  }
}

添加命令

 public class Add implements Cmd<Integer> { 
    public Add(Integer i) {
    }

 }

添加的解析函数

 public class ParseAdd implements Fn<String, Cmd<Integer>> { 
     public Cmd<Integer> apply(String option) {
       // parse the input and return the command with the arguments in there 
       // if (option == "add"  and args exist )
       // try parse args
       // i = Integer.parse(substring);

       return new Add(i); 
     }
 }

然后是ConsoleParser

public class ConsoleParser<A> {
  public static <A> ConsoleParser<A> cli(CliCommand <A> command) {
    ...
  }
  public ConsoleParser <A> or (CliCommand <A> command) {
    ...
  }

  public A parse(String arg) throws CliParseException {
     // 
  }

}

之后,您的程序可以像

一样编写
ConsoleParser<Cmd<Object>> parser = cli("add",new ParseAdd()) 
   .or(...)
   .or("quit", new ParseQuit();

Scanner input = new Scanner(System.in);
String parserArgs = input.nextLine(); 

while (true) 
{
    try {
       parser.parse(parserArgs).execute();
    } catch (CliParseException e) {
       // handle it somehow
    }
    parserArgs = input.nextLine();   
}

在这个例子中,Add太简单了,我想你实际上想要将String添加到一个或两个Numbers中,所以实际的ParseAdd方法需要一些上下文(比如已经存在的List),就像我的简单例子一样。

相关问题