这个问题在这里已经有了答案:
Is null an Object?
(14 个回答)
7年前关闭。
在 jls-4.1据说
There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3)
和
There is also a special null type
所以基本上
null
type 既不是原始类型也不是引用类型。但是为什么它可以容纳引用和
can always undergo a widening reference conversion to any reference type
如果它不被视为引用类型?或者它到底是某种引用类型?它可以被视为引用类型吗?
那么,问题的答案是什么 -
Is [null] a reference type or not
- 应该? Yes
或 No
?
最佳答案
首先,null
不是类型而是值。类型为引用类型的变量的值可能为 null,但不能使用 null
在需要引用类型的地方,不能声明 null
类型的变量并且你不能有类型参数 null
,例如你不能声明 List<null>
.
值 null
有一个特殊的“空类型”,它只在编译(和验证)期间相关,以便能够制定“空类型”可分配给引用类型的正式规则。但该
“空类型”不是引用类型。
从规范中添加一些引号:
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.
…
The null reference can always be assigned or cast to any reference type (§5.2, §5.3, §5.5).
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.
JVMS §4.10.1.2 :
Verification type hierarchy: top ____________/\____________ / \ / \ oneWord twoWord / | \ / \ / | \ / \ int float reference long double / \ / \_____________ / \ / \ uninitialized +------------------+ / \ | Java reference | / \ | type hierarchy | uninitializedThis uninitialized(Offset) +------------------+ | | null
关于java种类型和空引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26632104/