更新时间:2022-11-03 20:38:11
Up until JDK6, you could use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.
public class Hello {
static {
System.out.println("Hello, World!");
}
}
当然,您可以以java Hello
身份运行该程序,您将看到消息;但是,该命令也将失败,并显示以下消息:
Of course, you can run the program as java Hello
and you will see the message; however, the command will also fail with a message stating:
线程"main"中的异常java.lang.NoSuchMethodError:main
Exception in thread "main" java.lang.NoSuchMethodError: main
如其他人所述,
,您可以在打印消息后立即调用System.exit(0)
来避免NoSuchmethodError.
as noted by others, you can avoid the NoSuchmethodError by simply calling System.exit(0)
immediately after printing the message.
从JDK6开始,您不再看到来自static
初始化程序块的消息. 在此处详细说明.
As of JDK6 onward, you no longer see the message from the static
initializer block; details here.