2012-04-30 5 views
0

私はargs4jを使って自分のプログラムに与えられた引数を解析しています。args4j:解析中にCommandLineExceptionを投げた引数は何ですか?

ここでは、Date型の2つの引数を定義するコードを示します。ハンドラは、指定された日付を解析し、日付が不正な場合はCommandLineExceptionをスローします。

@Option(name="-b", metaVar="<beginDate>", handler=DateOptionHandler.class, usage="...") 
private Date beginDate; 

@Option(name="-e", metaVar="<endDate>", handler=DateOptionHandler.class, usage="...") 
private Date endDate; 

例外をスローするbeginDateまたはendDateの場合は、別のコード(int値)を返す必要があります。

は現在、私の主な方法は次のようになります。

CmdLineParser parser = new CmdLineParser(this); 
parser.setUsageWidth(120); 

try { 
    parser.parseArgument(args); 
} catch (CmdLineException e) { 
    /* Print usage if an error occurs during the parsing */ 
    System.err.println(e.getMessage()); 
    System.err.println("Usage : java LaunchProgram [options]"); 
    e.getParser().printUsage(System.err); 

    /* What I need to do : */ 
    if(optionWhichThrewTheException.equals("-b") return 2; 
    if(optionWhichThrewTheException.equals("-e") return 3; 

    /* Other arguments */ 
    return -1; 
} 

しかし、私は(私はCmdLineException方法を見て、私は何も見つからなかった)例外を投げた引数を知ることができる方法を見つけ出すことはできません。

パーズできないパラメータを取得する方法はありますか?

ご協力いただきありがとうございます。

+0

あなたがたstartDate場合== nullまたはendDateに== nullをチェックすることによって、それを伝えることはできないでしょうか? – mazaneicha

+0

お返事ありがとうございます。 残念ながら、beginDateとendDateはオプションです。したがって、beginDateが省略され、endDateが例外をスローすると、間違ったエラーコードが返されます。 – vb73

答えて

1

私はargs4jを使ったことが一度もありませんが、そのドキュメントを見ると、オプションハンドラによって例外がスローされたようです。だから、必要な情報を含むCmdLineExceptionのカスタムサブクラスをスローBDateOptionHandlerとEDateOptionHandlerを使用します。

public class BDateOptionHandler extends DateOptionHandler { 
    @Override 
    public int parseArguments(Parameters params) throws CmdLineException { 
     try { 
      super.parseArguments(params); 
     } 
     catch (CmdLineException e) { 
      throw new ErrorCodeCmdLineException(2); 
     } 
    } 
} 

public class EDateOptionHandler extends DateOptionHandler { 
    @Override 
    public int parseArguments(Parameters params) throws CmdLineException { 
     try { 
      super.parseArguments(params); 
     } 
     catch (CmdLineException e) { 
      throw new ErrorCodeCmdLineException(3); 
     } 
    } 
} 

... 
try { 
    parser.parseArgument(args); 
} 
catch (CmdLineException e) { 
    ... 
    if (e instanceof ErrorCodeCmdLineException) { 
     return ((ErrorCodeCmdLineException) e).getErrorCode(); 
    } 
} 
+0

トリックをありがとう、それは今動作します – vb73

関連する問題