Java main() Method Explained – Java的main()方法详解

最后修改: 2018年 5月 26日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Every program needs a place to start its execution; talking about Java programs, that’s the main method.
We’re so used to writing the main method during our code sessions, that we don’t even pay attention to its details. In this quick article, we’ll analyze this method and show some other ways of writing it.

2. Common Signature

2.常见的签名

The most common main method template is:
public static void main(String[] args) { }

That’s the way we’ve learned it, that’s the way the IDE autocompletes the code for us. But that’s not the only form this method can assume, there are some valid variants we can use and not every developer pays attention to this fact.

这是我们学习的方式,这是IDE为我们自动完成代码的方式。但这并不是这个方法唯一可以承担的形式,还有一些有效的变体我们可以使用,而不是每个开发者都会注意这个事实。

Before we dive into those method signatures, let’s review the meaning of each keyword of the common signature:

在我们深入研究这些方法签名之前,让我们回顾一下普通签名中每个关键字的含义。

  • public – access modifier, meaning global visibility
  • static – the method can be accessed straight from the class, we don’t have to instantiate an object to have a reference and use it
  • void – means that this method doesn’t return a value
  • main – the name of the method, that’s the identifier JVM looks for when executing a Java program

As for the args parameter, it represents the values received by the method. This is how we pass arguments to the program when we first start it.

至于args参数,它表示方法所收到的值。这就是我们在第一次启动程序时向其传递参数的方式。

The parameter args is an array of Strings. In the following example:

参数args是一个String数组。在下面的例子中。

java CommonMainMethodSignature foo bar

we’re executing a Java program called CommonMainMethodSignature and passing 2 arguments: foo and bar. Those values can be accessed inside of the main method as args[0] (having foo as value) and args[1] (having bar as value).

我们正在执行一个名为CommonMainMethodSignature的Java程序,并传递两个参数。foobar。这些值可以在main方法中作为args[0](以foo为值)和args[1](以bar为值)访问。

In the next example, we’re checking args to decide whether to load test or production parameters:

在下一个例子中,我们要检查args来决定是加载测试还是生产参数。

public static void main(String[] args) {
    if (args.length > 0) {
        if (args[0].equals("test")) {
            // load test parameters
        } else if (args[0].equals("production")) {
            // load production parameters
        }
    }
}

It’s always good to remember that IDEs can also pass arguments to the program.

记住IDE也可以向程序传递参数,这一点总是好的。

3. Different Ways to Write a main() Method

3.编写main()方法的不同方法

Let’s check some different ways to write the main method. Although they’re not very common, they’re valid signatures.

让我们看看一些不同的方法来写main方法。虽然它们不是很常见,但都是有效的签名。

Note that none of these are specific to the main method, they can be used with any Java method but they are also a valid part of the main method.

注意,这些都不是main方法所特有的,它们可以用于任何Java方法,但它们也是main方法的有效部分。

The square brackets can be placed near String, as in the common template, or near args on either side:

方括号可以放在String附近,就像在普通模板中那样,也可以放在args附近的任何一边。

public static void main(String []args) { }
public static void main(String args[]) { }

Arguments can be represented as varargs:

参数可以用varargs来表示。

public static void main(String...args) { }

We can even add strictfp for the main() method, which is used for compatibility between processors when working with floating point values:

我们甚至可以为main()方法添加strictfp,这是为了在处理浮点值时实现处理器之间的兼容。

public strictfp static void main(String[] args) { }

synchronized and final are also valid keywords for the main method but they won’t have an effect here.

synchronizedfinal也是main方法的有效关键字,但它们在这里不会产生影响。

On the other hand, final can be applied on args to prevent the array from being modified:

另一方面,final可以应用于args以防止数组被修改。

public static void main(final String[] args) { }

To end these examples, we can also write the main method with all of the above keywords (which, of course, you probably won’t ever use in a practical application):

为了结束这些例子,我们也可以用上述所有的关键字来编写main方法(当然,在实际应用中你可能永远不会用到)。

final static synchronized strictfp void main(final String[] args) { }

4. Having More Than One main() Methods

4.拥有一个以上的main()方法

We can also define more than one main method inside our application.

我们也可以在我们的应用程序中定义一个以上的main方法

In fact, some people use it as a primitive test technique to validate individual classes (although test frameworks like JUnit are way more indicated for this activity).

事实上,有些人把它作为一种原始的测试技术来验证单个的类(尽管像JUnit这样的测试框架更适用于这种活动)。

To specify which main method the JVM should execute as the entry point of our application, we use the MANIFEST.MF file. Inside the manifest, we can indicate the main class:

为了指定 JVM 应执行哪个 main 方法作为我们应用程序的入口,我们使用 MANIFEST.MF 文件。在清单中,我们可以指明主类。

Main-Class: mypackage.ClassWithMainMethod

This is mostly used when creating an executable .jar file. We indicate which class has the main method to start the execution, through the manifest file located at META-INF/MANIFEST.MF (encoded in UTF-8).

这主要是在创建可执行.jar文件时使用。我们通过位于META-INF/MANIFEST.MF的清单文件(用UTF-8编码),指出哪个类有main方法来开始执行。

5. Conclusion

5.结论

This tutorial described the details of the main method and some other forms it can assume, even the ones that aren’t very common to most of the developers.

本教程描述了main方法的细节以及它可以采取的一些其他形式,甚至是对大多数开发者来说并不十分常见的形式。

Keep in mind that, although all the examples that we’ve shown are valid in terms of syntax, they just serve the educational purpose and most of the time we’ll stick with the common signature to do our job.

请记住,尽管我们展示的所有例子在语法上都是有效的,但它们只是为了教育目的,大多数时候我们会坚持使用常用的签名来完成我们的工作。