How to check if an object is convertible to another type?
Let's say I have two string objects: "25000.00", and "1234" that my program gets at run time. How do I check if they are castable convertible to type double and int, respectively? Is开发者_运维问答 there a method or keyword in Java that does that already?
You can use the Integer.parseInt
or Double.parseDouble
static methods to do this. Each of these methods takes in a String
and converts them to an int
or double
as appropriate. You can check whether the string is convertible by calling this function. If the conversion is possible, it will be performed. Otherwise, the methods will throw NumberFormatException
s, which you can catch and respond to. For example:
try {
int value = Integer.parseInt(myString);
// Yes! An integer.
} catch (NumberFormatException nfe) {
// Not an integer
}
Hope this helps!
Just to clarify: String
is never castable to Double
or Integer
.
However, you can parse a String as a number using the Double.parseDouble
and Integer.parseInt
methods. If they are not parsable then a NumberFormatException
will be thrown. You can catch that and handle it appropriately.
Casting and parsing are quite different things.
EDIT: I see @BalusC has edited the question and changed "cast" to "convert". I guess my comments are redundant now :)
In C#, there is a method to check whether an object is can be cast to other object. But I guess, Integer.parseInt or Double.parseDouble suffice.
精彩评论