Search code examples
javacastingautoboxing

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


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


Solution

  • 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.