<分区>
例子.java
public class Example {
static final int i = 10;
static int j = 20;
static {
System.out.println("Example class loaded and initialized");
}
}
使用.java
import java.util.Scanner;
public class Use {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int ch = 1;
while(ch != 0) {
System.out.print("Enter choice: ");
ch = sc.nextInt();
if (ch == 1) {
System.out.println("Example's i = " + Example.i);
} else if(ch == 2){
System.out.println("Example's j = " + Example.j);
}
}
}
}
当我使用 java -verbose:class Use
运行时,输入为 1
然后输出为 10
即常量 我
值。但是 Example
类还没有加载。
但是,当我将输入作为 2
时,只有这样 Example
类被加载到 JVM 中,如详细输出所示,然后执行 Example 中的静态 block ,并初始化 j
的值,然后打印。
我的查询是:如果对于输入 1
,即当另一个类 Example
的静态最终(常量)值被请求时class Use
,那么如果 class Example
在此之前从未加载到 JVM 中,那么从哪里获取常量值?
static final i
何时以及如何初始化并存储到 JVM 内存中?