No. You have to make your own like this:
public int tryParseInt(String value, int defaultVal) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
return defaultVal;
}
}
...or
public Integer parseIntOrNull(String value) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
return null;
}
}
Apache Commons has an IntegerValidator class which appears to do what you want. Java provides no in-built method for doing this.
See here for the groupid/artifactid.
Code sample: (slightly verbose to show functionality clearly)
private boolean valueIsAndInt(String value) {
boolean returnValue = true;
if (null == new org.apache.commons.validator.routines.IntegerValidator().validate(value)) {
returnValue = false;
}
return returnValue;
}
Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.
Anyway, I'd just do this:
public Integer tryParse(Object obj) {
Integer retVal;
try {
retVal = Integer.parseInt((String) obj);
} catch (NumberFormatException nfe) {
retVal = 0; // or null if that is your preference
}
return retVal;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With