java:boolean instanceOf Boolean? [英] java: boolean instanceOf Boolean?

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

问题描述

我有点困惑:我有一个函数,一个对象作为参数。但是编译器不会抱怨,如果我只是传递一个原始,甚至认可一个布尔基元作为布尔对象。为什么会这样呢?

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 '将 Autoboxed Boolean ,它是一个 Object

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

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

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