Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following simple hello world in Java:

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

It works as expected, but oddly, it gives an error saying that the main method doesn't exist after.

$ javac A.java && java A
Hello world
Exception in thread "main" java.lang.NoSuchMethodError: main

Why? Should I ignore it? I even tried making a method called "main", but it changes nothing.

class A {
    static {
        main();
    }
    public static void main() {
        System.out.println("Hello world");
    }
}

$ javac A.java && java A
Hello world
Exception in thread "main" java.lang.NoSuchMethodError: main
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
214 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...