[英]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 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' 这是类'Class'的cast方法的源代码
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.
其他原语也是如此。
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. cast
不能真正为基元,做工精良因为它不能返回实际的基本类型的值,由于Java泛型...所以它最终会再次反正拳击。 And if you're not assigning straight to an int
value, it would have to be boxed for that reason too. 如果你没有直接赋值给
int
值,那么它也必须装箱。
So basically, if you want to convert to int
, just cast directly. 所以基本上,如果你想转换为
int
,只需直接转换。
isInstance
is documented to always return false
for primitives: isInstance
被记录总是返回false
的原语:
If this
Class
object represents a primitive type, this method returnsfalse
.如果此
Class
对象表示基本类型,则此方法返回false
。
... cast
probably should be too. ...
cast
可能应该也是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.