java - `int.class.cast(null)` 起作用的原因是什么?

标签 java casting

我刚刚尝试了以下操作:

System.out.println(int.class.cast(null));

这完全符合其规范中所述:

Casts an object to the class or interface represented by this {@code Class} object.
@param obj the object to be cast
@return the object after casting, or null if obj is null
@throws ClassCastException if the object is not null and is not assignable to the type T.

虽然如果 Class 是一些非原始类,这似乎很直观 - 毕竟 null 可以转换为所有类 - 我想知道为什么决定对于像 这样的原始类int 这不会导致 ClassCastException。我的理由是

Foo f = (Foo) null; // Okay
int a = (int) null; // Not okay: "Cannot cast from null to int"
                    // why doesn't Class#cast reflect this?

最佳答案

int.class的类型是 Class<Integer> ,所以它相当于强制转换为 Integer ,参见Class Literals :

The type of p.class, where p is the name of a primitive type (§4.2), is Class<B>, where B is the type of an expression of type p after boxing conversion (§5.1.7).

关于java - `int.class.cast(null)` 起作用的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36628653/

相关文章:

java - Liferay : how can i upload a image from portlet preferences?

java - 为什么调用父类(super class)的方法而不是子类的方法?

c++ - 如何在 C++ 中将动态数组转换为静态数组?

java - Hibernate 查询结果无法转换为 List<Subject>

c++ - 在 C/C++ 中将 int 转换为 bool

java - Docker 构建在下载期间挂起

java - 在Delphi和Java中是否有与 "result"变量类似的东西?

java - StringTemplate 和 FreeMarker 之间的主要区别是什么?

c++ - 可以禁止 C++ 中的隐式转换吗?

c# - 在 C# 中定义泛型类型的显式转换