java - 为什么在执行静态 block 时这个Float常量为null?

标签 java static-initialization

以下代码在执行时打印 nitesh null 而不是预期的 nitesh 130。 为什么 n 在执行静态 block 之前没有初始化?

class test
{
      static
      {
             System.out.println(test.str+"   "+test.n);
      }
      final static String str="nitesh";
      final static Float n=130f;
      public static void main(String []args)
      {
      }
}

最佳答案

str 是编译时常量 - n 不是,因为它是 Float 类型。如果将其更改为 final static float n = 130f,那么您将在静态初始化 block 中看到该值。

所以目前,在静态初始化 block 中,str 的值实际上被内联了——你的代码相当于:

System.out.println("nitesh   "+test.n);

来自 JLS section 15.28 (constant expressions) :

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following: [...]

Float 不是原始类型。

此外,即使没有内联,常量变量 str 也会在任何静态初始化程序 block 执行之前被初始化。来自 section 12.4.2 of the JLS (类初始化细节):

  • ...
  • Then, initialize the static fields of C which are constant variables (§4.12.4, §8.3.2, §9.3.1).
  • ...
  • Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

关于java - 为什么在执行静态 block 时这个Float常量为null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24202941/

相关文章:

java - 尝试使用 Java 请求 HTTPS 页面时,内容长度为 -1

C++静态函数指针数组的初始化

c++ - 静态初始化数组 union 结构

java - java反序列化时类初始化的顺序

java - 在 Android Activity 中从 Firebase 检索数据

java - 从 WEB-INF/lib 中的 Jar 中的类访问 tomcat web-app 中的文件

java - JAXB 向后兼容性

java - 在 SpringMVC 中启用日志记录,而不是使用 Spring-boot

C++ static-init-fiasco 例子

java - 如何在配置中将系统属性注入(inject)到静态bean中?