问题
The following program will print Hello world
when compiled with JDK 1.6
or lower versions of JDK
.
public class A { static { System.out.println("Hello world"); System.exit(0); } }
But JDK 1.7
or higher versions will generate a runtime error as follows when the above program is compiled.
Error: Main method not found in class A, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
I would like to know if there is some way to compile and run a program without main()
successfully in Java using JDK 1.7
or higher.
Thanks in advance.
回答1:
No. public static void main(String[] args)
is the main entry for all Java applications. There are frameworks that makes you believe there's no need of this method, like a unit test executed by JUnit, but the fact is that the framework has a main
method defined somewhere inside it, does the necessary calls for you and ends calling your code.
来源:https://stackoverflow.com/questions/23743949/is-it-possible-to-write-a-program-in-java-without-main-using-jdk-1-7-or-higher