Autoboxing/Unboxing while casting Integer to int using 'cast' method

不想你离开。 提交于 2019-12-20 02:54:08

问题


Here is a very simple case: I am trying to cast an Object type to a primitive like this:

Object object = Integer.valueOf(1234);

int result1 = int.class.cast(object); //throws ClassCastException: Cannot convert java.lang.integer to int

int result2 = (int)object; //works fine

This is the source code of cast method of class 'Class'

public T cast(Object obj) {
    if (obj != null && !isInstance(obj))
        throw new ClassCastException(cannotCastMsg(obj));
    return (T) obj;
}

private String cannotCastMsg(Object obj) {
    return "Cannot cast " + obj.getClass().getName() + " to " + getName();
}

Why is this happening? Same is happening with other primitives too.

Live Example


回答1:


cast can't really work well for primitives, given that it can't return a value of the actual primitive type, due to generics in Java... so it would end up boxing again anyway. And if you're not assigning straight to an int value, it would have to be boxed for that reason too.

So basically, if you want to convert to int, just cast directly.

isInstance is documented to always return false for primitives:

If this Class object represents a primitive type, this method returns false.

... cast probably should be too.



来源:https://stackoverflow.com/questions/33052463/autoboxing-unboxing-while-casting-integer-to-int-using-cast-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!