Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 384
Anmol Gupta Avatar asked Aug 08 '26 21:08

Anmol Gupta


1 Answers

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.

like image 173
Jon Skeet Avatar answered Aug 11 '26 10:08

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!