在Java中如何在没有main方法的情况下执行静态块?
VM首先寻找主要方法(至少是最新版本),然后开始执行包含静态块的程序。因此,如果没有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
热门推荐
10 病人祝福语老师寄语简短
11 新娘生孩子祝福语简短
12 婆婆66岁祝福语简短
13 今天孩子高考祝福语简短
14 送彩票生日祝福语简短
15 分别祝福语简短情话英文
16 画室揭牌仪式祝福语简短
17 女友妈妈生日祝福语简短
18 离别赠言离职祝福语简短