Is it possible to write a program in Java without main() using JDK 1.7 or higher? [duplicate]

旧城冷巷雨未停 提交于 2019-12-20 02:47:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!