Java 中静态块何时何地执行?
java 8object oriented programmingprogramming更新于 2025/9/11 18:20:17
静态块是带有 static 关键字的代码块。通常,静态块用于初始化静态成员。JVM 在类加载时,会在主方法之前执行静态块。
示例
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

