【发布时间】:2016-02-09 19:53:43
【问题描述】:
我有一个接受字符串clientid 的方法,它有以下要求:
-
clientid可以是大于零的正数。但如果是负数或零,则抛出IllegalArgumentException并发送消息。 -
clientid不能是null或空字符串。但如果是的话,请抛出IllegalArgumentException并发送消息。 -
clientid也可以是普通字符串。例如 - 它可以是abcdefgh或任何其他字符串。
import static com.google.common.base.Preconditions.checkArgument;
public Builder setClientId(String clientid) {
checkArgument(!Strings.isNullOrEmpty(clientid), "clientid cannot not be null or an empty string, found '%s'.",
clientid);
final Long id = Longs.tryParse(clientid);
if (id != null) {
checkArgument(id.longValue() > 0, "clientid must not be negative or zero, found '%s'.", clientid);
}
this.clientid = clientid;
return this;
}
此代码运行良好。现在的问题是,我不能使用高于版本 11 的 guava 库。如果我确实使用它,那么它会给我们使用这个库的客户带来问题,所以简而言之,我正在寻找替代这条线 final Long id = Longs.tryParse(clientid); 而不使用 guava 或可能与较旧的 guava 版本 11 一起使用。由于 Longs.tryParse 方法是在 Guava 14 或更高版本中添加的。
最好的方法是什么?我们可以从 Apache Commons 使用什么?
【问题讨论】:
-
为什么不直接使用 try{ }catch(NumberformatException ne){}
-
那看起来很难看..想避免这种情况..还有其他方法吗?
-
好吧,公平地说,之前也是 4 行 :)
-
这里是给猪涂口红的问题,你选哪个色系。
-
是的,就是这样。我想摆脱 catch 块,所以这就是我之前使用 Longs.tryParse 的原因,但如果除了我之前知道的没有其他方法,那么我将使用它。
标签: java guava apache-commons preconditions