JavaMain方法
经过上一节我们知道最终main方法中会通过pthread_create创建一个新的线程来执行JavaMain方法,下面我们慢慢来剖析JavaMain核心流程,在此列出来的代码我们也只列出来核心代码,后续就不再做此说明
JavaMain
java.c 文件中JavaMain方法中主要初始化Jvm虚拟机,加载Java程序需要使用到的mainClass, 找到main方法,执行main,这样我们Java main就成功的被调用了
int JNICALL JavaMain(void * _args)
{
/* Initialize the virtual machine */
if (!InitializeJVM(&vm, &env, &ifn)) {
JLI_ReportErrorMessage(JVM_ERROR1);
exit(1);
}
//Get the application's main class. It also checks if the main method exists.
jclass mainClass = LoadMainClass(env, mode, what);
/*
* The LoadMainClass not only loads the main class, it will also ensure
* that the main method's signature is correct, therefore further checking
* is not required. The main method is invoked here so that extraneous java
* stacks are not in the application stack trace.
*/
jmethodID mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
"([Ljava/lang/String;)V");
/* Invoke main method. */
(*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);
}
执行流程说明:
- InitializeJVM初始化Jvm,这个方法内部逻辑比较复杂先不要去挖,看完主流程,它的功能就是初始化Java虚拟机,包含如下模块,内存管理,GC,类加载模块等
- LoadMainClass ,获取应用程序的Main Class,也就是带main方法class ,jclass声明下面列出来了,是一个空无成员变量的class指针,由此可知这个指针肯定就是指向了一个class在内存中的地址
class _jobject