Why is the Java main method static?

前端 未结 30 2170
离开以前
离开以前 2020-11-22 01:41

The method signature of a Java main() method is:

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

Is the

30条回答
  •  心在旅途
    2020-11-22 01:56

    Why public static void main(String[] args) ?

    This is how Java Language is designed and Java Virtual Machine is designed and written.

    Oracle Java Language Specification

    Check out Chapter 12 Execution - Section 12.1.4 Invoke Test.main:

    Finally, after completion of the initialization for class Test (during which other consequential loading, linking, and initializing may have occurred), the method main of Test is invoked.

    The method main must be declared public, static, and void. It must accept a single argument that is an array of strings. This method can be declared as either

    public static void main(String[] args)
    

    or

    public static void main(String... args)
    

    Oracle Java Virtual Machine Specification

    Check out Chapter 2 Java Programming Language Concepts - Section 2.17 Execution:

    The Java virtual machine starts execution by invoking the method main of some specified class and passing it a single argument, which is an array of strings. This causes the specified class to be loaded (§2.17.2), linked (§2.17.3) to other types that it uses, and initialized (§2.17.4). The method main must be declared public, static, and void.

    Oracle OpenJDK Source

    Download and extract the source jar and see how JVM is written, check out ../launcher/java.c, which contains native C code behind command java [-options] class [args...]:

    /*
     * Get the application's main class.
     * ... ...
     */
    if (jarfile != 0) {
        mainClassName = GetMainClassName(env, jarfile);
    
    ... ...
    
        mainClass = LoadClass(env, classname);
        if(mainClass == NULL) { /* exception occured */
    
    ... ...
    
    /* Get the application's main method */
    mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
                                       "([Ljava/lang/String;)V");
    
    ... ...
    
    {    /* Make sure the main method is public */
        jint mods;
        jmethodID mid;
        jobject obj = (*env)->ToReflectedMethod(env, mainClass,
                                                mainID, JNI_TRUE);
    
    ... ...
    
    /* Build argument array */
    mainArgs = NewPlatformStringArray(env, argv, argc);
    if (mainArgs == NULL) {
        ReportExceptionDescription(env);
        goto leave;
    }
    
    /* Invoke main method. */
    (*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);
    
    ... ...
    

提交回复
热议问题