java 如何检查对象是否可以转换为另一种类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4664350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:25:04  来源:igfitidea点击:

How to check if an object is convertible to another type?

javatype-conversion

提问by Terence Ponce

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 castableconvertible to type double and int, respectively? Is there a method or keyword in Java that does that already?

假设我有两个字符串对象:“25000.00”和“1234”,它们是我的程序在运行时获得的。如何检查,如果他们是浇注料,可转换成double型和INT分别?Java 中是否有方法或关键字可以做到这一点?

回答by templatetypedef

You can use the Integer.parseIntor Double.parseDoublestatic methods to do this. Each of these methods takes in a Stringand converts them to an intor doubleas 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 NumberFormatExceptions, which you can catch and respond to. For example:

您可以使用Integer.parseIntDouble.parseDouble静态方法来执行此操作。这些方法中的每一个都接受 aString并将它们适当地转换为 anintdouble。您可以通过调用此函数来检查字符串是否可转换。如果转换是可能的,它将被执行。否则,这些方法将抛出NumberFormatExceptions,您可以捕获并响应它。例如:

try {
    int value = Integer.parseInt(myString);
    // Yes!  An integer.
} catch (NumberFormatException nfe) {
    // Not an integer
}

Hope this helps!

希望这可以帮助!

回答by Cameron Skinner

Just to clarify: Stringis nevercastable to Doubleor Integer.

只是为了澄清:String从来没有强制转换DoubleInteger

However, you can parsea String as a number using the Double.parseDoubleand Integer.parseIntmethods. If they are not parsable then a NumberFormatExceptionwill be thrown. You can catch that and handle it appropriately.

但是,您可以使用和方法将字符串解析为数字。如果它们不可解析,则将抛出 a 。你可以抓住它并适当地处理它。Double.parseDoubleInteger.parseIntNumberFormatException

Castingand parsingare quite different things.

转换解析是完全不同的事情。

EDIT: I see @BalusC has edited the question and changed "cast" to "convert". I guess my comments are redundant now :)

编辑:我看到@BalusC 编辑了问题并将“演员”更改为“转换”。我想我的评论现在是多余的:)

回答by ron_IT

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.

在 C# 中,有一种方法可以检查一个对象是否可以转换为其他对象。但我想,Integer.parseInt 或 Double.parseDouble 就足够了。