问题描述
我喜欢中的建议java中的将字符串转换为Int的字符串-可能是不良数据,需要避免异常以实现可解析int的实用程序方法,但如果无法解析该字符串,则返回默认值.
I like the suggestion in String to Int in java - Likely bad data, need to avoid exceptions to implement a utility method that parses an int, but returns a default value if the string cannot be parsed.
public static int parseInt(String s, int defaultValue) {
if (s == null) return defaultValue;
try {
return Integer.parseInt(s);
} catch (NumberFormatException x) {
return defaultValue;
}
}
是否存在现有的开源库(例如,来自Apache Commons或google)以及其他数据类型(例如boolean,float,double,long等)实现了这一目标?
Is there an existing open source library (from apache commons, or google, for example) that implements this as well as for other data types such as boolean, float, double, long, etc?
推荐答案
Apache Commons Lang 具有此类 org.apache.commons.lang3.math.NumberUtils
以及方便的方法转变.换句话说,如果有错误,您可以指定默认值.例如
Apache Commons Lang has the class org.apache.commons.lang3.math.NumberUtils
with convenient methods for convert. In another way, you can specify a default value if there is a error. e.g.
NumberUtils.toLong("") => 0L
NumberUtils.toLong(null, 1L) => 1L
NumberUtils.toByte(null) => 0
NumberUtils.toByte("1", 0) => 1
这篇关于具有parseInt,parseLong,parseDouble等可以接受默认值且不引发异常的Java库吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!