问题
How can jvm enter in default class:
class try1
{
public static void main(String args[])
{
...
}
}
In it how does JVM access this method?
In packages, if a class is 'default' its public methods cant be accessed from outside the package, so how does jvm enter this class?
回答1:
It is not JVM itself who invokes main
method. This is rather a job of Java launcher, i.e. java.exe
.
Java launcher is a small program written in C that uses regular JNI functions:
JNI_CreateJavaVM
to create a new instance of JVM and to obtain an instance ofJNIEnv
;JNIEnv::FindClass
to locate the main class specified in the command line;JNIEnv::GetStaticMethodID
to findpublic static void main(String[])
method in class #2.JNIEnv::CallStaticVoidMethod
to invoke the method found in #3.
In fact, JNI allows you to work with all classes, methods and fields, even with private
modifier.
回答2:
First of all the JVM does not enter the method, it invokes (calls) it (yes, it matters). The keyword public
declares that the method can be accessed from anywhere (different packages
); the static
keyword declares that you can call the method without instatiating the class
(among other things) and as far as I know the class that contains the main method is always public
.
回答3:
You explicitly told java what class to load on the command line or in a .jar's Manifest if you're running an executable jar.
The Java Specification Chapter 12 goes briefly into what happens when the JVM starts up. (The JVM Specification Chapter 5 covers it in more detail.)
In short:
java try1
will load the try1
class, then link, verify, resolve, and initialize it.
Once that's done, it will look for a main method that is public
, static
, and void
that accepts an array of String
s, then it will execute that method.
The JVM doesn't care that your class wasn't public. As the first class loaded, it is the current compilation unit and initial access control is calculated from it.
来源:https://stackoverflow.com/questions/24557989/how-does-jvm-enter-in-public-static-void-main