我想更好地理解 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
变量 - 但您可以转换 boolean
到 Boolean
使用自动装箱。
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/