概述
How can I cast an Object to an int in java?
解决方案
If you're sure that this object is an Integer :
int i = (Integer) object;
Or, starting from Java 7, you can equivalently write:
int i = (int) object;
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 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.
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);
It can throw a NumberFormatException if your object isn't really a String with an integer as content.
Resources :
On the same topic :
最后
以上就是懵懂宝马为你收集整理的java int 转 object,如何将Object转换为int的全部内容,希望文章能够帮你解决java int 转 object,如何将Object转换为int所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复