为什么我会为int.class强制转换获得类强制转换异常 [英] Why do I get class cast exception for int.class cast

查看:131
本文介绍了为什么我会为int.class强制转换获得类强制转换异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的程序中,我无法理解为什么 ClassCastException 来自 int.class

In below program I fail to understand why there is ClassCastException for cast from int.class

更新:
我应该指定我知道原始类型是什么。 我不明白为什么int.class提供了破坏的实现?

  public static void main(String[] args) {
    System.out.println(DataType.INT.getValue(Integer.class));
    System.out.println(DataType.INT.getValue(int.class));//Class cast exception here
}

enum DataType {
    INT {
        @Override
        public <T> T getValue(Class<T> toClass) {
            return toClass.cast(1000);//ClassCastException here for int.class
        }
    };
    public abstract <T> T getValue(Class<T> toClass);

}


推荐答案

好的,在浏览了一些链接并尝试了一些代码后,我发现: -

Ok, after going through some links, and trying out some code, I found out that: -


  • int.class == Integer.TYPE == int

  • int.class != Integer.class

  • int.class == Integer.TYPE == int
  • int.class != Integer.class

所以,值 int.class 是表示类型 int 的Class对象。

So, the value of int.class is Class object representing the type int.

因此,当您使用 int.class DataType.INT 时c $ c>, toClass 包含 int ,你无法调用 cast 。可能是因为它没有从 Object 类扩展。因为, cast 方法在内部使用 isinstance 来检查调用类型是否为对象输入与否。

So, when you invoke your DataType.INT with int.class, the toClass containts int, on which you cannot invoke cast. May be because it does not extend from Object class. Because, cast method internally uses isinstance to check whether the invoking type is an Object type or not.

public T cast(Object obj) {
if (obj != null && !isInstance(obj))
    throw new ClassCastException();
return (T) obj;
}

因此,如果调用 cast的类型不是 Object 的实例,当然 primitive 类型不是,它将返回 false ,因此 ClassCastException

So, if the type that invokes cast is not an instance of Object, which of course primitive types are not, it will return false, and hence a ClassCastException.

这篇关于为什么我会为int.class强制转换获得类强制转换异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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