我正在尝试运行这段代码,但我发现了静态最终的行为:代码运行时没有执行A的静态块。请给我提供原因。
class A {
final static int a=9;
static { //this block is not executing ??
System.out.println("static block of A");
}
}
class Manager {
static {
System.out.println("manager sib");
}
public static void main(String ...arg) {
System.out.println("main");
System.out.println(A.a);
}
}为什么A类的静态块不运行?
发布于 2013-03-20 04:05:58
问题是A.a是一个constant variable。
基本类型或字符串类型的变量称为常量变量,该变量是最终类型,并使用编译时常量表达式(§15.28)进行初始化。
因此,您的Manager.main方法将完全按照如下方式进行编译:
public static void main(String ...arg) {
System.out.println("main");
System.out.println(9);
}不再有对A.a的真正引用,因此A类甚至不需要存在,更不用说初始化了。(您可以删除A.class,但仍可运行Manager。)
如果您依赖于使用A.a来确保类型已初始化,则不应添加no-op方法:
public static void ensureClassIsInitialized() {
} 然后从你的main方法中调用它。然而,需要这样做是非常不寻常的。
发布于 2013-03-20 04:29:32
规范http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf第4.12.1节说,
A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).因为您只访问常量,所以不需要初始化类。
发布于 2015-06-10 05:11:05
您可以强制加载所需的任何类:
public final class ClassUtils {
private ClassUtils() {}
public static void forceLoad(Class<?>... classes) {
for (Class<?> clazz : classes) {
try {
Class.forName(clazz.getName(), true, clazz.getClassLoader());
} catch (ClassNotFoundException e) {
throw new AssertionError(clazz.getName(), e);
}
}
}
}
class Manager {
static {
ClassUtils.forceLoad(A.class);
// ...
}
public static void main(String ...arg) {
// ...
}
}https://stackoverflow.com/questions/15509337
复制相似问题