问题描述
我有点困惑:我有一个函数,它接受一个对象作为参数.但是,如果我只传递一个原语,甚至将布尔原语识别为布尔对象,编译器不会抱怨.为什么呢?
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.