如何将Object转换为int [英] How to cast an Object to an int
问题描述
如何在java中将对象强制转换为int?
How can I cast an Object to an int in java?
推荐答案
如果您确定此对象是整数
:
int i = (Integer) object;
或者,从Java 7开始,您可以等效地写:
Or, starting from Java 7, you can equivalently write:
int i = (int) object;
小心,它可以抛出 ClassCastException
=http://download.oracle.com/javase/6/docs/api/java/lang/Integer.html\"rel =noreferrer> 整数
和 NullPointerException
如果您的对象 null
。
Beware, it can throw a ClassCastException
if your object isn't an Integer
and a NullPointerException
if your object is null
.
这样您就可以假设您的对象是一个Integer(包装的int),你将它拆箱成一个int。
This way you assume that your Object is an Integer (the wrapped int) and you unbox it into an int.
int
是一个原语,所以它不能存储为对象
,唯一的方法是将 int
视为/盒装为整数
然后存储为对象
。
int
is a primitive so it can't be stored as an Object
, the only way is to have an int
considered/boxed as an Integer
then stored as an Object
.
如果您的对象是 String
,那么您可以使用 Integer.valueOf()
方法将其转换为简单的int:
If your object is a String
, then you can use the Integer.valueOf()
method to convert it into a simple int :
int i = Integer.valueOf((String) object);
它可以抛出 NumberFormatException
如果您的对象实际上不是 String
,以整数作为内容。
It can throw a NumberFormatException
if your object isn't really a String
with an integer as content.
资源:
- Oracle.com - Autoboxing
- Oracle.com - Primitive Data types
关于同一主题:
- Java: What's the difference between autoboxing and casting?
- Autoboxing: So I can write: Integer i = 0; instead of: Integer i = new Integer(0);
- Convert Object into primitive int
这篇关于如何将Object转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!