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.

live example

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 returns false.

... cast should too.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -