Hello world works but then gets error that there's no main?

前端 未结 6 612
星月不相逢
星月不相逢 2020-12-09 09:57

I have the following simple hello world in Java:

class A {
    static {
        System.out.println(\"Hello world\");
    }
}

It works as ex

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 10:34

    When your class is loaded, static initializers will be run, and then the JVM will try to invoke the main method. You can fix this by adding one more line to your static initializer:

    public class HelloWorld {
        static {
            System.out.println("Look ma', no hands!");
            System.exit(0);
        }
    }
    

    This will stop the JVM before it tries to invoke your main method.

    Also note, this will not execute in Java 7. Java 7 looks for a main method before initializing the class.

提交回复
热议问题