静块何时何地会在 Java 中执行?


静态块是一段带有 static 关键字的代码块。通常,这些代码块用于初始化静态成员。JVM 会在类加载时在 main 方法之前执行静态块。

示例

 演示

public class MyClass {
   static{
      System.out.println("Hello this is a static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}

输出

Hello this is a static block
This is main method

执行静态块

JVM 首先会查找 main 方法(至少是最新版本),然后开始执行包含静态块在内的程序。因此,如果没有 main 方法,你无法执行静态块。

示例

 演示

public class Sample {
   static {
      System.out.println("Hello how are you");
   }
}

由于上述程序没有 main 方法,如果你编译并执行它,将收到一条错误消息。

C:\Sample>javac StaticBlockExample.java
C:\Sample>java StaticBlockExample
Error: Main method not found in class StaticBlockExample, please define the main
method as: public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

如果你想执行静态块,则需要有 Main 方法,并且该类的静态块会在 main 方法之前执行。

示例

 演示

public class StaticBlockExample {
   static {
      System.out.println("This is static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}

输出

This is static block
This is main method

更新于: 30-Jul-2019

2000+ 浏览

开启你的 职业生涯

完成课程获得认证

开始使用
广告
© . All rights reserved.