java - Autoboxing/Unboxing while casting Integer to int using 'cast' method -
here simple case: trying cast object type primitive this:
object object = integer.valueof(1234); int result1 = int.class.cast(object); //throws classcastexception: cannot convert java.lang.integer int int result2 = (int)object; //works fine
this 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() + " " + getname(); }
why happening? same happening other primitives too.
cast
can't work primitives, given can't return value of actual primitive type, due generics in java... end boxing again anyway. , if you're not assigning straight int
value, have boxed reason too.
so basically, if want convert int
, cast directly.
isinstance
documented return false
primitives:
if
class
object represents primitive type, method returnsfalse
.
... cast
should too.
Comments
Post a Comment