isAssignable来自引用和基元类型 [英] isAssignableFrom with reference and primitive types

查看:83
本文介绍了isAssignable来自引用和基元类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如:
$



$ b

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

布尔原语;
布尔referenceType = true;
primitive = referenceType;
System.out.println(primitive); // true

我知道,当分配基元< - >引用装箱/ ,但我曾想过,因此isAssignableFrom将在上面的前两个示例中返回true。



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

解决方案

你不能实际赋予布尔 code> value改为布尔值变量 - 但您可以将转换为布尔值布尔使用自动装箱。



JavaDocs 使规则非常清晰:


确定此Class对象表示的类或接口
是否为
,或者是
还是超类
或超级接口,班级或
接口由指定的
Class参数表示。它返回true如果
那么;否则返回false。如果
这个Class对象表示一个
基元类型,如果指定的Class参数
正好是这个Class对象,则此方法返回
true;
,否则返回false。



I'd like to get a better understanding of the isAssignableFrom behaviour in Java between primitive and reference types.

Eg:

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

I know that when assigning primitives <-> reference that boxing / unboxing occurs as required, but I'd have thought that therefore isAssignableFrom would return true in the first two examples above.

Could someone please explain why it returns false, and what the appropriate test here is?

解决方案

You can't actually assign a boolean value to a Boolean variable - but you can convert from boolean to Boolean using auto-boxing.

The JavaDocs make the rules pretty clear:

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.

这篇关于isAssignable来自引用和基元类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆