Hello world 工作正常,但随后出现没有 main 的错误? [英] Hello world works but then gets error that there's no main?

查看:22
本文介绍了Hello world 工作正常,但随后出现没有 main 的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Java 中有以下简单的 hello world:

I have the following simple hello world in Java:

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

它按预期工作,但奇怪的是,它给出了一个错误,指出 main 方法在之后不存在.

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

为什么?我应该忽略它吗?我什至尝试创建一个名为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

推荐答案

当你的类被加载时,static 初始化器将被运行,然后 JVM 将尝试调用 main方法.您可以通过在 static 初始值设定项中再添加一行来解决此问题:

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);
    }
}

这将在 JVM 尝试调用您的 main 方法之前停止它.

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

还要注意,这不会在 Java 7 中执行.Java 7 在初始化类之前查找 main 方法.

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

这篇关于Hello world 工作正常,但随后出现没有 main 的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆