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

标签 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 不得为负数或数字为零” 或者可能是其他一些好消息。如果可能的话,如何使用 Guava 先决条件来做到这一点?

根据建议,我使用以下代码:

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

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

关于java - 如何将字符串解释为负数或零并相应地抛出 IAE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34890066/

相关文章:

JSON:序列化 Guava optional

java - Guava - 为什么 IncomparableValueException 不公开?

Java:弱前置条件和强后置条件,如何?

c++ - Stroustrup 书中的前后条件

java - 无法使用 SpringSource Tool Suite 计算构建计划

java - Spring LDAP 示例

java - 你会如何递归地编写这段代码?

java - 私有(private)构造函数和实例 - 多项选择

java - 使用 Guava CharMatcher 作为类中的静态字段。 CharMatcher 线程安全吗?

semantics - 公理语义 - 如何计算最弱的前提条件