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/16432521/

相关文章:

java - 如何从 SQLite 随机设置文本到按钮而不重复?

ArrayList 和 Array 的 Java 通用问题

c# - 没有从派生到基础类的装箱转换

java - Java 中泛型的深拷贝

斯卡拉 : Match of parameter Type

java - 同步方法还是使用 spring @transactional?

java - 我可以自动下载带链的 X.509 证书吗?

java - RESTful Web 服务无法正确处理请求方法

c# - C# 中的变体规则

regex - 关于正则表达式的证明