在Java中,null是一个对象
吗?
java.lang.Object
的方法,例如equals()
。但事实并非如此-对null的任何方法调用都会导致NullPointerException
。
Java语言规范对此问题的表述如下:i
也是特殊的。 - Gaurav Mallnull
是可以被分配的类型_”:1)在代码中,null
是_null字面量_,而不是_null类型_。2)通常情况下,在Java中无法将类型分配给变量,参见JLS 4.1:“_有两种数据值可以存储在变量中:原始值(§4.2)和引用值(§4.3)_”。可以通过null
字面量来分配_null引用_。...续... - Gerold Broserlength
属性的数组 和 java.awt.geom.Point2D
的子类。 - Gerold Brosernull instanceof Object
返回false。通常情况下,这取决于你从哪个角度看待它,相信谁更多。不,不是这样的……
null
字面值是Object
类型吗?”除了Michael Borgwardt上面引用的JLS 4.1:以及JLS 4.10:null字面值始终是null类型。
或者JLS 4.10.2:类型T的子类型是所有类型U,使得T是U的超类型,并且是null类型。
[强调是我的。]null类型的直接超类型是除了null类型本身之外的所有引用类型。
true.toString(); // Cannot invoke toString() on the primitive type boolean
null.toString(); // Cannot invoke toString() on the primitive type null
javac
,它是:true.toString(); // error: boolean cannot be dereferenced
null.toString(); // error: <null> cannot be dereferenced
null
是除原始类型以外的其他类型。根据JLS 4.1:相反,
null
有点丑。
null
很美。你建议一个引用类型变量的默认值是什么?任意位组合吗?欢迎进入访问违规或更糟的指针地狱!
实际上,与null相关联的有三个项目(也可以参见JLS 3.10.7):
null
是一种类型和值。
null
字面值。JVM_global final null_type null = new null_type();
还要注意JLS 3.9:
有时会错误地假定各种字符序列是关键字:
null
不是关键字,而是null字面值(§3.10.7)。
null instanceof <any type>
null instanceof <any type>
应该被认为是会评估为 true
,对吗?乍一看是这样,但是 JLS 15.20.2 给出了深入的解答:
[...]
instanceof
运算符的结果是true
,如果 RelationalExpression 的值不是null
[...]. 否则结果为false
。
[强调是我添加的。]
从应用程序员的角度来看,你自己问什么更有意义:
Giving false
and thus indicating that a reference expression is not of a type exposed to us, i.e. indicating it's not referencing anything useful to us
or giving true
, thus informing us that the expression evaluates to a special reference, the null reference, referencing an "object" we don't know whether it even exists and which is of the special null type which has no name, is not exposed to us but via the null literal, is a subtype of any type including multiple inheritance and is to be ignored anyway? Consider also the more practical example:
class Car implements Vehicle {
...
Vehicle car = null;
...
boolean b = car instanceof Car; // True? There's not even an instance
... // which could be of type Car.
这也导致了:
instanceof
不能正确表示null
的对象性?它被称为instanceof
而不是sameorsubtypeof
。这意味着我们比较的是一个实例的类型和一种类型,而不是两种类型。现在null
的意思是:“没有实例”,如果没有实例,就没有实例的类型。显然,将空值与某个值进行比较应该会得到false
。
或者用一个“更真实”的例子来说:
正如迈克尔总结的那样:“null是特殊的”。
Null表示缺少一个对象。
不,它不是一个对象。
null
):
你可能想了解关于Null Object Pattern(我不推荐使用)的内容。请查看C2 Wiki或Wikipedia以获取更多关于该模式的信息。还有一个特殊的null类型,即表达式
null
的类型,它没有名称。因为null类型没有名称,所以不可能声明null类型的变量或将其强制转换为null类型。null引用是null类型表达式的唯一可能值。null引用始终可以转换为任何引用类型。实际上,程序员可以忽略null类型,只需假装null
是可以是任何引用类型的特殊字面量。
null instanceof <任何类型>
的结果也将返回 false
。 - Bombe
Null
的类型(实际上是一种特质),它具有一个名为null
的单例实例。需要注意的是,该翻译并未包含解释或其他任何额外内容。 - Carl Smotricznull
相当的是nil
,它是NilClass的一个实例。 - Eliot Sykesnull instanceof Object
是false,但typeof(null)
返回'object'
。在这种情况下它是一个对象吗?谁知道呢。 - Don Hatch