标签:
argparse4j 是 Python argparse 命令行解析器的 Java 语言移植版。这个要比spring AspectJ 更简单,更方便实现。
<dependency> <groupId>net.sourceforge.argparse4j</groupId> <artifactId>argparse4j</artifactId> <version>0.3.0</version> </dependency>
1 package Argparse4j; 2 3 import net.sourceforge.argparse4j.ArgumentParsers; 4 import net.sourceforge.argparse4j.impl.Arguments; 5 import net.sourceforge.argparse4j.inf.ArgumentParser; 6 import net.sourceforge.argparse4j.inf.ArgumentParserException; 7 import net.sourceforge.argparse4j.inf.Namespace; 8 9 import java.util.Collection; 10 import java.util.Collections; 11 import java.util.List; 12 13 14 /** 15 * Hello world! 16 * 17 */ 18 public class App 19 { 20 private static interface Accumulate { 21 int accumulate(Collection<Integer> ints); 22 } 23 24 private static class Sum implements Accumulate { 25 @Override 26 public int accumulate(Collection<Integer> ints) { 27 int sum = 0; 28 for (Integer i : ints) { 29 sum += i; 30 } 31 return sum; 32 } 33 34 @Override 35 public String toString() { 36 return getClass().getSimpleName(); 37 } 38 } 39 40 private static class Max implements Accumulate { 41 @Override 42 public int accumulate(Collection<Integer> ints) { 43 return Collections.max(ints); 44 } 45 46 @Override 47 public String toString() { 48 return getClass().getSimpleName(); 49 } 50 } 51 52 public static void main(String[] args) { 53 ArgumentParser parser = ArgumentParsers.newArgumentParser("app") 54 .description("Process some integers."); 55 parser.addArgument("integers") 56 .metavar("N") 57 .type(Integer.class) 58 .nargs("+") 59 .help("an integer for the accumulator"); 60 parser.addArgument("--sum") 61 .dest("accumulate") 62 .action(Arguments.storeConst()) 63 .setConst(new Sum()) 64 .setDefault(new Max()) 65 .help("sum the integers (default: find the max)"); 66 try { 67 Namespace res = parser.parseArgs(args); 68 69 System.out.println(res); 70 System.out.print("----"); 71 System.out.println(((Accumulate) res.get("accumulate")) 72 .accumulate((List<Integer>) res.get("integers"))); 73 System.out.println(res.get("accumulate")); 74 System.out.println(res.get("integers")); 75 } catch (ArgumentParserException e) { 76 parser.handleError(e); 77 } 78 } 79 80 }
java -jar com.Argparse4j-1.0-SNAPSHOT.jar 1 X 4 --sum
Namespace(integers=[1, 2, 4], accumulate=Sum)
----7
Sum
[1, 2, 4]
java -jar com.Argparse4j-1.0-SNAPSHOT.jar 1 3 4
Namespace(integers=[1, 3, 4], accumulate=Max)
----4
Max
[1, 3, 4]
标签:
原文地址:http://www.cnblogs.com/shouhongxiao/p/5798587.html