Static block in Java not executed

前端 未结 5 1430
长情又很酷
长情又很酷 2020-11-28 03:32
class Test {
    public static void main(String arg[]) {    
        System.out.println("**MAIN METHOD");
        System.out.println(Mno.VAL); // SOP(9090)         


        
5条回答
  •  粉色の甜心
    2020-11-28 04:12

    The reason why the class is not loaded is that VAL is final AND it is initialised with a constant expression (9090). If, and only if, those two conditions are met, the constant is evaluated at compile time and "hardcoded" where needed.

    To prevent the expression from being evaluated at compile time (and to make the JVM load your class), you can either:

    • remove the final keyword:

      static int VAL = 9090; //not a constant variable any more
      
    • or change the right hand side expression to something non constant (even if the variable is still final):

      final static int VAL = getInt(); //not a constant expression any more
      static int getInt() { return 9090; }
      

提交回复
热议问题