没有主方法的情况下如何运行Java程序?

问题描述:

可能重复:
在控制台上打印消息而不使用main()方法 >

Possible Duplicate:
Printing message on Console without using main() method

有人可以建议如何在不编写主方法的情况下运行Java程序.

Can someone suggest how can a JAVA program run without writing a main method..

例如:

System.out.println("Main not required to print this");

如何使用类中的 public static void main(String arg [])在控制台上打印以上行.

How can the above line be printed on console without using the public static void main(String arg[]) in the class.

直到JDK6,您都可以使用

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.