how does jvm enter in public static void main?

淺唱寂寞╮ 提交于 2020-02-10 17:49:51

问题


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:

  1. JNI_CreateJavaVM to create a new instance of JVM and to obtain an instance of JNIEnv;
  2. JNIEnv::FindClass to locate the main class specified in the command line;
  3. JNIEnv::GetStaticMethodID to find public static void main(String[]) method in class #2.
  4. 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 Strings, 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!