java - 具有引用和原始类型的 isAssignableFrom

标签 java generics types

我想更好地理解 Java 中基本类型和引用类型之间的 isAssignableFrom 行为。

例如:

System.out.println(boolean.class.isAssignableFrom(Boolean.class)); // false
System.out.println(Boolean.class.isAssignableFrom(boolean.class)); // false

boolean primitive;
Boolean referenceType = true;
primitive = referenceType;
System.out.println(primitive); // true

我知道在分配原语时 <-> 引用会根据需要进行装箱/拆箱,但我认为 isAssignableFrom 因此会在上面的前两个示例中返回 true。

有人可以解释为什么它返回 false 吗?这里的适当测试是什么?

最佳答案

您不能实际上boolean 值分配给Boolean 变量 - 但您可以转换 booleanBoolean 使用自动装箱。

JavaDocs使规则非常明确:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

关于java - 具有引用和原始类型的 isAssignableFrom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1650614/

相关文章:

java - 确保类型参数正确

linux - 是否有一个 header 提供类似于 uint64_t 的类型,用于 Linux 或 gcc 中的 float 和 double ?

uitableview - SWIFT:使用未声明的类型 "detailViewController"

java - 阿克曼函数

java - 如何用方向键移动矩形?

C# 泛型 : does compiler creates only one specialized generic type for different reference types?

swift - 带开关的通用功能

MySQL非常长的数字数据类型

java - 具有类特定属性的最佳解决方案

java - 从网站上的 PHP 脚本运行本地主机 Java Applet