我有点困惑:我有一个函数,它接受一个对象作为参数。但是,如果我只是传递一个原语,甚至将 boolean 原语识别为 boolean 对象,编译器也不会提示。为什么呢?
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
。
关于java: boolean instanceOf boolean 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3600686/