Why does Java (> = 7 version) not support running the program without the main method?

class WithoutMain { static { System.out.println("Without main class!!!"); System.exit(0); } } 

when I try to run the above code in java version greater than 7, I get below the error. The program was successfully compiled, but the main class was not found. The main class must contain a method: public static void main (String [] args).

can someone tell me why Java does not support starting a program without main after java7

+3
java static jvm
Feb 29 '16 at 12:04 on
source share
3 answers

AFAIK, this change was specific to Java 7. In Java 8, you can do this. You cannot do this in Java 7 because it is looking for a method without loading the first class that fails. In any case, it has been changed to Java 8.

 public class Main { static { System.out.println("Without main class!!! with " + System.getProperty("java.version")); System.exit(0); } } 

prints

 Without main class!!! with 1.8.0_66 

Note: this will kill the entire program. If you want the program to continue to work without the core, you can do it

 public class Main { static { // do something which starts threads System.out.println("Without main class!!! with " + System.getProperty("java.version")); if (true) throw new ThreadDeath(); } } 

This will prevent the error message from appearing, but leave the background thread running if there is a thread without a daemon.

+7
Feb 29 '16 at 12:24
source share

static partition

 static { System.out.println("Without main class!!!"); System.exit(0); } 

will be executed every time the JVM loads the class into memory, but if you want to run the Java application, you will need the main method, because this is the starting point of each java application, if you do not define it, then the JVM has no idea why to begin.




you can expand your code and do something like:

 class WithoutMain { static { System.out.println("Static section!!"); } public static void main(String[] args){ System.out.println("Main class!!!"); } } 

and first there will be the first static section, and then the code that you define in the main method.

+1
Feb 29 '16 at 12:08
source share

The static method is loaded by the class every time the JVM is launched, and the class is loaded into it, but there is nothing that calls it or displays its contents inside the JVM. Like every language (which I know), you need a handler for your arguments, and in the case of Java, this is the main() method.

0
Feb 29 '16 at 12:11
source share



All Articles