自动装箱/展开时取消装箱使用“强制转换”方法将整数转换为整数 [英] Autoboxing/Unboxing while casting Integer to int using 'cast' method

查看:138
本文介绍了自动装箱/展开时取消装箱使用“强制转换”方法将整数转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一个非常简单的例子:我试图将一个Object类型转换为这样的原语:

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

这是类'Class'的cast方法的源代码

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.

实例

推荐答案

cast 无法真正适合原语,因为它不能返回值实际的原始类型,由于在Java中的泛型...所以它会结束拳击再次。如果你不直接赋值给 int 的值,那么它也必须用盒子来表示。

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.

所以基本上,如果你想转换为 int ,只需直接转换。

So basically, if you want to convert to int, just cast directly.

isInstance 文档总是为原语返回 false


对象表示一个原始类型,此方法返回 false

If this Class object represents a primitive type, this method returns false.

... cast 可能也应该这样。

... cast probably should be too.

这篇关于自动装箱/展开时取消装箱使用“强制转换”方法将整数转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆