问题
I'm using some API by restTemplate. The API returns a key whose type is integer.
But I'm not sure of that value, so I want to check whether the key is really an integer or not. I think it might be a string.
What is the best way of checking if the value is really integer?
added: I mean that some API might return value like below. {id : 10} or {id : "10"}
回答1:
Object x = someApi();
if (x instanceof Integer)
Note that if someApi() returns type Integer the only possibilities of something returned are:
- an
Integer null
In which case you can:
if (x == null) {
// not an Integer
} else {
// yes an Integer
}
回答2:
If what you receive is a String, you can try to parse it into an integer, if it fails, it's because it was not an integer after all. Something like this:
public static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
回答3:
One possibility is to use Integer.valueOf(String)
回答4:
Assuming your API return value can either be an Integer or String you can do something like this:
Integer getValue(Object valueFromAPI){
return (valueFromAPI != null ? Integer.valueOf(valueFromAPI.toString()) : null);
}
来源:https://stackoverflow.com/questions/8336607/how-to-check-if-the-value-is-integer-in-java