如何将字符串解释为负数或零并相应地抛出 IAE?

How to interpret string as a negative number or zero and throw IAE accordingly?

我有一个接受字符串的方法,它可以是数字字符串或普通字符串。

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;
}

有没有更好的方法?

我认为最简单的方法如下:

 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:

Returns:

the integer value represented by string, or null if string has a length of zero or cannot be parsed as an integer value

此外,它在收到 null 时抛出 NullPointerException


编辑: 但是,如果允许任何其他字符串,代码将更改为:

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;
  }

此代码将接受所有为严格正整数或 non-null 和 non-empty.

的字符串