如何将对象转换为 int [英] How to cast an Object to an int

查看:40
本文介绍了如何将对象转换为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在java中将对象转换为int?

How can I cast an Object to an int in java?

推荐答案

如果你确定这个对象是一个 Integer :

If you're sure that this object is an Integer :

int i = (Integer) object;

或者,从 Java 7 开始,您可以等效地编写:

Or, starting from Java 7, you can equivalently write:

int i = (int) object;

当心,它可能会抛出一个 ClassCastException 如果您的对象不是 IntegerNullPointerException 如果您的对象是 null.

Beware, it can throw a ClassCastException if your object isn't an Integer and a NullPointerException if your object is null.

这样你就假设你的对象是一个整数(包装的整数),然后你把它拆箱成一个整数.

This way you assume that your Object is an Integer (the wrapped int) and you unbox it into an int.

int 是一个原语,所以它不能存储为 Object,唯一的方法是考虑/装箱一个 int作为 Integer 然后存储为 Object.

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.

资源:

关于同一主题:

这篇关于如何将对象转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆