为什么静态块中的代码不会执行?
这里我做了一个程序,当我打印main
static
块中的constant
不执行..但是当我打印执行的stat
是否有任何重要的java static final
..? 请解释
package com.test.doubt;` class Doubt { public static final int constant = 123; public static int stat = 123; static { System.out.println("Static Block"); } } public class MyProgram { public static void main(String[] args) { System.out.println(Doubt.constant); } }
static final int
将直接编译为代码作为其值。 也就是说,JVM看到并正在执行:
System.out.println(123);
并且你根本没有触及你恰当命名的Doubt
类(这是一个不以这种方式指定常量的参数,顺便说一下。如果你改变了这个值,你必须重新编译每个引用类)
你的代码没有初始化Doubt
类,正是因为Doubt.constant
是一个常量。 它的值在编译时被放入MyProgram
中 – 你甚至可以在编译后删除Doubt.class
,你的程序仍会运行。
跑
javap -c com.test.doubt.MyProgram
仔细看看编译后代码的样子。
有关常量表达式的构成,请参见JLS的第15.28节 。 例如,这仍然是一个常数:
public static final String FOO = "Foo";
以及所有这些:
public static final String FOO = "Foo"; public static final String BAR = "Bar"; public static final String FOOBAR = FOO + BAR;
……但这不会
public static final String NOT_A_CONSTANT = "Foo".substring(0, 1);
- 排球SSL – 主机名未经validation
- 防止在Rotate上重新加载WebView – Android Studio
- 如何访问android项目的根目录中的文件,java路径
- 一次登录应用程序 – FirebaseAuth
- 为什么String类有复制构造函数?
- 为什么Google Cloud Endpoints不支持简单对象返回类型?
- Android聊天在DataSnapshot.getValue()上崩溃,以获取时间戳
- 为什么在Java中,(“string”)。除了(var).equals(“string”)之外,推荐使用equals(var)?
- 如何将ArrayList从AsyncTask返回到另一个类?