且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“错误:在 MyClass 类中找不到 Main 方法,请将 main 方法定义为...";

更新时间:2022-06-21 06:38:24

当您使用 java 命令从命令行运行 Java 应用程序时,例如,

When you use the java command to run a Java application from the command line, e.g.,

java some.AppName arg1 arg2 ...

该命令加载您指定的类,然后查找名为 main 的入口点方法.更具体地说,它正在寻找一个声明如下的方法:

the command loads the class that you nominated and then looks for the entry point method called main. More specifically, it is looking for a method that is declared as follows:

package some;
public class AppName {
    ...
    public static void main(final String[] args) {
        // body of main method follows
        ...
    }
}

入口点方法的具体要求是:

The specific requirements for the entry point method are:

  1. 该方法必须在指定的类中.
  2. 方法的名称必须是main";正是那个大写1.
  3. 方法必须是public.
  4. 方法必须是static 2.
  5. 方法的返回类型必须是void.
  6. 该方法必须只有一个参数,并且参数的类型必须是 String[] 3.
  1. The method must be in the nominated class.
  2. The name of the method must be "main" with exactly that capitalization1.
  3. The method must be public.
  4. The method must be static 2.
  5. The method's return type must be void.
  6. The method must have exactly one argument and argument's type must be String[] 3.

(参数可以使用varargs语法声明;例如String... args.见这个问题 了解更多信息.String[] 参数用于从命令行传递参数,即使您的应用程序不接受命令行参数.)

(The argument may be declared using varargs syntax; e.g. String... args. See this question for more information. The String[] argument is used to pass the arguments from the command line, and is required even if your application takes no command-line arguments.)

如果上述要求中的任何一个不满足,java 命令将失败并显示消息的某些变体:

If anyone of the above requirements is not satisfied, the java command will fail with some variant of the message:

Error: Main method not found in class MyClass, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

或者,如果您运行的是非常旧版本的 Java:

Or, if you are running an extremely old version of Java:

java.lang.NoSuchMethodError: main
Exception in thread "main"

如果您遇到此错误,请检查您是否有一个 main 方法并且它满足上面列出的所有六个要求.

If you encounter this error, check that you have a main method and that it satisfies all of the six requirements listed above.

1 - 一个真正晦涩的变体是当main"中的一个或多个字符出现时不是 LATIN-1 字符……而是一个 Unicode 字符,看起来像显示时对应的 LATIN-1 字符.
2 - 此处解释了为什么要求方法是静态的.
3 - String 必须对应于 java.lang.String 而不是一个名为 String 的自定义类隐藏它.

1 - One really obscure variation of this is when one or more of the characters in "main" is NOT a LATIN-1 character … but a Unicode character that looks like the corresponding LATIN-1 character when displayed.
2 - Here is an explanation of why the method is required to be static.
3 - String must correspond to java.lang.String and not to a custom class named String hiding it.