我刚刚尝试了以下操作:
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
, wherep
is the name of a primitive type (§4.2), isClass<B>
, whereB
is the type of an expression of typep
after boxing conversion (§5.1.7).
关于java - `int.class.cast(null)` 起作用的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36628653/