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

时间:2016-01-20 01:37:37

标签: java guava preconditions

我有一个方法,我接受一个字符串,可以作为字符串或普通字符串编号。

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

有没有更好的方法呢?

1 个答案:

答案 0 :(得分: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表示的整数值,如果null的长度为零或无法解析为整数值,则为string

此外,当收到NullPointerException时,它会抛出null

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

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

此代码将接受所有严格为正整数或非空且非空的字符串。