4

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

6
  • 2
    Java is statically typed, so the API must have a fixed return type. I don't see what the point of this question is. Commented Dec 1, 2011 at 4:43
  • Is the return type actually Integer or is it a string representation of a number? Commented Dec 1, 2011 at 4:45
  • @NullUserException: The API might return an Object or something silly like that. Commented Dec 1, 2011 at 4:46
  • @ChrisParton That would be a silly way to do things. Commented Dec 1, 2011 at 4:47
  • what't the exact signature of the function? Commented Dec 1, 2011 at 4:47

4 Answers 4

12

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

This fails for me in Java 7 when the string has other characters in it too.
3

One possibility is to use Integer.valueOf(String)

1 Comment

This assumes the object is a string. What if it's actually an Integer? This is where I don't understand the OP's question: they ask as if the return type is unknown (and unknowable)
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.