可以自定义工具方法,例如:public static int parseInt(String s, int defaultValue) {
if (s == null)
return defaultValue;
try {
return Integer.parseInt(s);
} catch (NumberFormatException x) {
return defaultValue;
}
}也可以使用org.apache.commons.lang3.math.NumberUtils提供的工具类,需要导入commons-lang3.jar包。
使用示例:
NumberUtils.toInt(userInfo.getUserPort(), 0);// 转换失败返回默认值0源码示例:
/**
* @param str the string to convert, may be null
* @param defaultValue the default value
* @return the int represented by the string, or the default if conversion fails
* @since 2.1
*/
public static int toInt(String str, int defaultValue) {
if(str == null) {
return defaultValue;
}
try {
return Integer.parseInt(str);
} catch (NumberFormatException nfe) {
return defaultValue;
}
}
本文介绍了如何将字符串安全地转换为整数的方法,包括自定义工具方法和使用org.apache.commons.lang3.math.NumberUtils类实现。这两种方法都能在转换失败时返回默认值。
65

被折叠的 条评论
为什么被折叠?



