java: boolean instanceOf 布尔值? [英] java: boolean instanceOf Boolean?

查看:33
本文介绍了java: boolean instanceOf 布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑:我有一个函数,它接受一个对象作为参数.但是,如果我只传递一个原语,甚至将布尔原语识别为布尔对象,编译器不会抱怨.为什么呢?

I'm a bit confused: I have a function, that takes an Object as argument. But the compiler does not complain if I just pass a primitive and even recognizes a boolean primitive as Boolean Object. Why is that so?

public String test(Object value)
{
   if (! (value instanceof Boolean) ) return "invalid";
   if (((Boolean) value).booleanValue() == true ) return "yes";
   if (((Boolean) value).booleanValue() == false ) return "no";
   return "dunno";
}

String result = test(true);  // will result in "yes"

推荐答案

因为原语 'true' 将是 AutoboxedBoolean 并且是一个 Object.

Because primitive 'true' will be Autoboxed to Boolean and which is a Object.

这篇关于java: boolean instanceOf 布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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