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

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

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

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...