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


当前回答

最后,找到了适合您的规范的最佳实现。

public int tellMyNumber(Object any) {
    return 42;
}

其他回答

不可能做到。int不是一个对象,它是一个基本类型。你可以将它转换为Integer,然后获取int。

 Integer i = (Integer) o; // throws ClassCastException if o.getClass() != Integer.class

 int num = i; //Java 1.5 or higher

答:

int i = ( Integer ) yourObject;

如果你的对象已经是一个整数,它将顺利运行。即:

Object yourObject = 1;
//  cast here

or

Object yourObject = new Integer(1);
//  cast here

etc.

如果你的对象是其他类型的对象,你需要先将它(如果可能的话)转换为int类型:

String s = "1";
Object yourObject = Integer.parseInt(s);
//  cast here

Or

String s = "1";
Object yourObject = Integer.valueOf( s );
//  cast here

我在处理来自GSON的数据时使用一行程序:

int i = object != null ? Double.valueOf(object.toString()).intValue() : 0;
so divide1=me.getValue()/2;

int divide1 = (Integer) me.getValue()/2;

最后,找到了适合您的规范的最佳实现。

public int tellMyNumber(Object any) {
    return 42;
}