2

文字列を受け入れるメソッドがあり、それは文字列または通常の文字列として数値にすることができます。

public Builder setClientId(String clientId) {
    checkNotNull(clientId, "clientId cannot be null");
    checkArgument(clientId.length() > 0, "clientId can't be an empty string");
    this.clientId = clientId;
    return this;
}

clientIdここで、誰かが負の数値"-12345"またはゼロとして渡されているかどうかを確認してみましょう。"0"これを解釈してIllegalArgumentException、メッセージをスローする"clientid must not be negative or zero as a number"か、他の適切なメッセージである可能性があります。可能であれば、グアバの前提条件を使用してこれを行うにはどうすればよいですか?

提案に従って、私は以下のコードを使用しています:

public Builder setClientId(String clientId) {
    checkNotNull(clientId, "clientId cannot be null");
    checkArgument(clientId.length() > 0, "clientId can't be an empty string");
    checkArgument(!clientid.matches("-\\d+|0"), "clientid must not be negative or zero");
    this.clientId = clientId;
    return this;
}

それを行うより良い方法はありますか?

4

1 に答える 1

2

これを行う最も簡単な方法は次のとおりだと思います。

 public Builder setClientId(String clientId) {
    final Integer id = Ints.tryParse(clientId);
    checkArgument(id != null && id.intValue() > 0,
      "clientId must be a positive number, found: '%s'.", clientId);
    this.clientId = clientId;
    return this;
  }

このメソッドを呼び出すと、次のようになります。

.setClientId("+-2"); 
// java.lang.IllegalArgumentException: clientId must be a positive number, found: '+-2'.

.setClientId("-1"); 
// java.lang.IllegalArgumentException: clientId must be a positive number, found: '-1'.

.setClientId(null); 
// java.lang.NullPointerException

このコードはInts.tryParse. JavaDoc から:

戻り値:

で表される整数値string、または長さがゼロであるnullstring整数値として解析できない場合

NullPointerExceptionまた、 anullを受信すると aをスローします。


編集:ただし、他の文字列が許可されている場合、コードは次のように変更されます。

public Builder setClientId(String clientId) {
    checkArgument(!Strings.isNullOrEmpty(clientId),
      "clientId may not be null or an empty string, found '%s'.", clientId);
    final Integer id = Ints.tryParse(clientId);
    if (id != null) {
      checkArgument(id.intValue() > 0,
        "clientId must be a positive number, found: '%s'.", clientId);
    }
    this.clientId = clientId;
    return this;
  }

このコードは、厳密に正の整数または非 null および空でないすべての文字列を受け入れます。

于 2016-01-20T08:41:30.183 に答える