How to check if the value is integer in java? [duplicate]

前提是你 提交于 2019-12-18 05:15:13

问题


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

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