null 真的很特别吗?

Is null really special or not?

根据JLS 4.1

There is also a special null type, the type of the expression null (§3.10.7, §15.8.1), which has no name.

Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type.

The null reference is the only possible value of an expression of null type.

The null reference can always undergo a widening reference conversion to any reference type.

In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.

如果 null 真的可以是任何引用类型那么为什么 IS-A 测试失败了? 即

null instanceof Object      //returns false

null instanceof String      //returns false

object instanceof Type 检查引用 object 引用的对象的 运行时类型。例如,

 Animal animal = new Dog();
 animal instanceof Dog; // returns true

instanceof 查找引用引用的实际对象并测试其运行时类型。 null 不引用堆上的实际对象,因此 null instanceof Type 当然必须 return false。

null 视为 Object 完全相反的。可以将任何值分配给对象,同样可以将任何引用类型设置为 null。如果 RHS 为 Object,则 instanceof 始终为真,同样,如果 null 为左轴,则 instanceof 始终为假。从逻辑上讲,如果一种语言的结构是 everything (Object),它也应该有一个结构来定义 nothing (null)。

现在,回到你原来的问题。在 java 中,假设您有

Object o = null,其等效字节码指令为.

0: aconst_null --> Null reference is pushed onto the stack
1: astore_1    --> store a reference into local variable 1 (i.e, Object o)

所以在后台 null 是以不同的 方式处理的。 System.out.println(null instanceof Object); 会给出 false,因为根据语言的语义 nullnothing 并且不能有任何实例。它只是一个占位符,表示 reference 指向 valid but junk value.