http://blog.csdn.net/w47_csdn/article/details/77855126
可以自定義工具方法,例如:
public static int parseInt(String s, int defaultValue) {
if (s == null) return defaultValue;
try {
return Integer.parseInt(s);
} catch (NumberFormatException x) {
return defaultValue;
}
}
其他的parseLong、parseDouble與之類似。
也可以使用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;
- }
- }