当前位置: 首页 > 工具软件 > args4j > 使用案例 >

【Java Args4J】简单了解Args4J库

阎涵忍
2023-12-01

Args4J

修改翻译整理
相关资源:https://blog.csdn.net/zhishangdezuomo/article/details/25201029/
https://blog.csdn.net/dnc8371/article/details/107260230?utm_medium=distribute.pc_relevant_download.none-task-blog-baidujs-1.nonecase&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-baidujs-1.nonecase

用args4j库在Java应用程序中解析命令行参数

  • Args4J使用一个被称为Option的类来保存输入的参数.
  • 根据Option类来应用参数,每个参数可以对应一个类中的属性.
  • 类中属性用Annotation注解,在Annotation中给出该参数的选项, 还可以配置其他有用的信息.该Annotation就是 Option 注解:

从类的main(final String[])函数接收的命令行参数是传递给parseArguments(String[])方法的parseArguments(String[])数组。

Option 注解

  • 标记接收命令行开关值的field/setter。

  • 该注解可以放置在 T type的 fieldvoid methodName(T value)形式的方法上。

  • 它的access modified可以是任何内容,但如果不是public的,则application需要在允许 args4j 访问field/method的安全上下文中运行(请参阅AccessibleObject.setAccessible(boolean))。

  • 注释的行为因 T而异 — 字段的类型或方法的参数。the type of the field or the parameter of the method.

    • Boolean Switch 布尔开关
      当 T 是 boolean 时,它表示一个采用“-OPT”形式的布尔选项。设置此选项后,该属性将设置为 true。

    • String Switch 字符串开关
      当 T 是 String 时,它表示一个接受一个操作数的选项。操作数的值设置为属性。

    • Enum Switch 枚举开关
      当 T 从 Enum 派生时,它表示一个带有操作数的选项,该操作数必须是枚举常量之一。操作数和枚举常量名称之间的比较以不区分大小写的方式完成。
      例如,以下定义将代表命令行选项,如“-coin penny”或“-coin DIME”,但诸如“-coin”或“-coin abc”之类的东西是错误的。

       enum Coin { 
       PENNY,NICKEL,DIME,QUARTER 
       }
      
      class Option{
        @Option(name="-coin")
      	public Coin coin;
       }
      
    • File Switch 文件
      当 T 是 File 时,它​​代表一个选项,它以文件/目录名作为操作数。

所需元素摘要

该注解有5个字段 其中name是必须的,其他四个是可选的.

  • String
    name 名称
    选项的名称,例如“-foo”或“-bar”。

  • 可选元素摘要

  • Class <? extends OptionHandler>
    handler
    指定处理命令行参数的 OptionHandler。

  • String metaVar
    当该选项带有操作数时,使用屏幕将显示这样的内容:
    需要布尔值
    指定该选项是必需的。

  • String usage
    用于显示使用屏幕的帮助字符串。

例子(提供的两个链接中)

 package test.args4j;  
   
 import org.kohsuke.args4j.Argument;  
 import org.kohsuke.args4j.CmdLineException;  
 import org.kohsuke.args4j.CmdLineParser;  
 import org.kohsuke.args4j.ExampleMode;  
 import org.kohsuke.args4j.Option;  
 import org.kohsuke.args4j.spi.BooleanOptionHandler;  
   
 import java.io.File;  
 import java.io.IOException;  
 import java.util.ArrayList;  
 import java.util.List;  
   
 public class TestArgs4J {  
   // 利用Option注解来定义一个boolean 命令行参数 其参数name为 -re ,required指定该参数是必须的  
   @Option(name = "-re", usage = "recursively run something", required = true)  
   private boolean recursive;  
   
   //利用Option注解定义一个File 命令行参数, name为-o, 输入时候知道该file的路径就可以了  
   //metaVar 用来设定显示 使用方式时候的输出,这个输出为-o OUTPUT : output to this file  
   //如果不指定该属性 则使用默认的代替 为-o FILE : output to this file  
   @Option(name = "-o", usage = "output to this file", metaVar = "OUTPUT")  
   private File out = new File(".");  
   
   //If 'usage' value is empty, the option will not be displayed  
     // in the usage screen.  
   //注意该处没有指定 usage 属性 或者指定usage 但是其值为空的 如usage = "",这样当使用  
   //parser.printExample(ExampleMode.ALL) 请注意下面第92行的输出  
   @Option(name = "-str", required = true)  
   //@Option(name = "-str", usage = "测试", required = true)  // 该行 -str参数有用  
   // no usage  
     
   private String str = "(default value)";  
   
   // 整数参数  
   @Option(name = "-n", usage = "repeat <n> times\nusage can have new lines in it and also it can be verrry long")  
   private int num = -1;  
  
// using 'handler=...' allows you to specify a custom OptionHandler  
// implementation class. This allows you to bind a standard Java type  
// with a non-standard option syntax  
//指定一个特定的handler   
   @Option(name = "-custom", handler=BooleanOptionHandler.class,usage="boolean value for checking the custom handler")  
    private boolean data;  
  
// receives other command line parameters than options  
   @Argument  
   private List<String> arguments = new ArrayList<String>();  
  
   public static void main(String[] args) throws IOException {  
       new TestArgs4J().doMain(args);  
}  
  
   public void doMain(String[] args) throws IOException {  
//Creates a new command line owner that parses arguments/options  
  
             and set them into the given object.  
             CmdLineParser parser = new CmdLineParser(this);  
      
    try {  
    // parse the arguments.  
    parser.parseArgument(args);  
      
    // you can parse additional arguments if you want.  
    // parser.parseArgument("more","args");  
      
    // after parsing arguments, you should check  
    // if enough arguments are given.  
    if (arguments.isEmpty())  
    throw new CmdLineException("No argument is given");  
      
    } catch (CmdLineException e) {  
    // if there's a problem in the command line,  
    // you'll get this exception. this will report  
    // an error message.  
    System.err.println(e.getMessage());  //打印出错消息  
    System.err.println("java SampleMain [options...] arguments...");  
    // print the list of available options  
    parser.printUsage(System.err);  // 打印参数的用法  
    System.err.println();  
      
    System.err.println("测试!!!!!");  
    // print option sample. This is useful some time  
    System.err.println("  Example: java SampleMain"  
    + parser.printExample(ExampleMode.ALL));          
      
    // 注意 在Option中如果没有指定 usage 属性,  
    System.err.println("/n 2.........");                  
      
    //则这两行程序不会输出该参数的使用的  
      
    System.err.println(" 2 Example2: java SampleMain"    
      
    //注意 在Option中如果没有指定 usage 属性,  
    + parser.printExample(ExampleMode.REQUIRED));     
      
    //则这两行程序不会输出该参数的使用的  
    return;  
    }  
      
    // this will redirect the output to the specified output  
    System.out.println(out);  
      
    if (recursive)  
    System.out.println("-r flag is set");  
      
         if (data)  
    System.out.println("-custom flag is set");  
      
         System.out.println("-str was " + str);  
       
         if (num >= 0)  
           System.out.println("-n was " + num);  
       
         // access non-option arguments  
         System.out.println("other arguments are:");  
         for (String s : arguments)  
           System.out.println(s);  
       }  
   
 }  

例子2

package examples.dustin.commandline.args4j;
 
import static java.lang.System.out;
 
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
 
import java.io.IOException;
 
/**
 * Demonstrate args4j.
 */
public class Main
{
   @Option(name="-v", aliases="--verbose", usage="Print verbose status.")
   private boolean verbose;
 
   @Option(name="-f", aliases="--file", usage="Fully qualified path and name of file.", required=true)
   private String fileName;
 
   private void doMain(final String[] arguments) throws IOException
   {
      final CmdLineParser parser = new CmdLineParser(this);
      if (arguments.length < 1)
      {
         parser.printUsage(out);
         System.exit(-1);
      }
      try
      {
         parser.parseArgument(arguments);
      }
      catch (CmdLineException clEx)
      {
         out.println("ERROR: Unable to parse command-line options: " + clEx);
      }
      out.println("The file '" + fileName + "' was provided and verbosity is set to '" + verbose + "'.");
   }
 
   /**
    * Executable function demonstrating Args4j command-line processing.
    *
    * @param arguments Command-line arguments to be processed with Args4j.
    */
   public static void main(final String[] arguments)
   {
      final Main instance = new Main();
      try
      {
         instance.doMain(arguments);
      }
      catch (IOException ioEx)
      {
         out.println("ERROR: I/O Exception encountered: " + ioEx);
      }
   }
}
 类似资料: