你好世界的工作,但然后得到错误,没有主要的? [英] Hello world works but then gets error that there's no main?

查看:163
本文介绍了你好世界的工作,但然后得到错误,没有主要的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

为什么?我应该忽略它吗?我甚至试过制作一个名为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会查找<$ c初始化类之前的$ c> main 方法。

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

这篇关于你好世界的工作,但然后得到错误,没有主要的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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