java种类型和空引用

标签 java

这个问题在这里已经有了答案:





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 - 应该? YesNo ?

最佳答案

首先,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/

相关文章:

java - 如何使用 Elastic Search Java API 设置父/子关系?

java - 在 JVM 上进行定期线程转储 - ThreadMXBean 与 JVMTI 代理

Java:如何从 HTML 中的嵌套 <div> 中提取分离的文本?

java - 如何在 Java 的 If/Else 语句中为变量赋值后返回该变量?

java - 将 JMenuItem 传递给 Controller ​​类

java - 使用 Hibernate 保留原始 Java Enum

java - 使用巴比伦算法计算平方根

java - Spring对普通方法的异常处理

c# - 从中文或日文字符集生成随机字符串

java - 虚拟键盘与 Nimbus 冲突