Static block is not executing in JDK 7, “Main method not found”, but works in JDK 1.5

前端 未结 9 2083
我寻月下人不归
我寻月下人不归 2021-01-07 20:19

I have written a simple class with one static block

class Hello
{

  static {
           System.out.println(\"Hello\");
       System.exit(0);
     }
}
         


        
9条回答
  •  时光说笑
    2021-01-07 21:07

    If you read the JLS Chapter 12 carefully (version 5 or 7), it is not specified when the static initialization of the "main" class should occur. Indeed there is a Bug Report that complains about this.

    What is specified is that the "main" class will be initialized (and the static initializers will be run) before the entry point method is called. That is specified in JLS 12.4.1

    I can't explain why they changed this, or find where they documented the change. But apparently it did change. If you wanted the real explanation you would need to ask the Sun / Oracle engineers responsible.

    (FWIW, I think that this is a good change. Having the static initialization happen and then having the program fail due to the not finding the entry point is unexpected behaviour, and unexpected is bad if there is no good justification.)

提交回复
热议问题