Why is my static block of code not executing?

I am trying to run this code, but I figured out this final behavior with statics: the code works without executing static block A. Please provide me a reason.

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(Aa); } } 

Why is a class A static block not executing?

+4
source share
3 answers

The problem is that Aa is a variable.

A variable of primitive type or String type, which is final and initialized by the expression of the compile-time constant (ยง15.28), is called a constant variable.

Therefore, your Manager.main method Manager.main compiled as if it were:

 public static void main(String ...arg) { System.out.println("main"); System.out.println(9); } 

There is no real reference to Aa , so class A should not even exist, not to mention initialization. (You can remove A.class and still run Manager .)

If you rely on using Aa to make sure the type is initialized, you should not add the no-op method instead:

 public static void ensureClassIsInitialized() { } 

then just call it from your main method. This is very unusual, but you need to do it.

+7
source

Specification http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf Section 4.12.1. He speaks,

A variable of a primitive type or String type, which is final and initialized by the compile-time constant constant (ยง15.28), is called a constant variable. Regardless of whether the variable is constant or not, it can have for class initialization (ยง12.4.1), binary compatibility (ยง13.1, ยง13.4.9) and specific (ยง16).

Since you only access the constant, class initialization is not required.
+1
source

You can force download any class you need:

 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) { // ... } } 
0
source

All Articles