Java library that has parseInt, parseLong, parseDouble, etc that accept default values and don't throw exceptions?

匿名 (未验证) 提交于 2019-12-03 01:04:01

问题:

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

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?

回答1:

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 


回答2:

Guava has several tryParse methods that return null on a failed parse, e.g. Ints.tryParse, Floats.tryParse, etc



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!