关于类加载器(ClassLoader)

ClassLoader 是干什么用的?
在 JVM 中类(Class)是怎么执行的?
我们以如下代码为例

Student s = new Student();
s.play();
Student s2 = new Student();
执行流程
JVM 作为操作系统的一个进程在系统中执行,那么系统会为 JVM 分配一块内存空间,这块内存空
间被 JVM 分为 3 大块(栈区堆区方法区


一般而言,对象在堆(Heap)中创建,但是一些特殊的对象会在方法区中创建。
第 1 步
当 JVM 执行第一行代码“ Student s = new Student();”时
JVM 先碰到了 Student 类,“ Student s = new Student();”
此时,JVM 将查看方法区中是否有 Student 对应的 Class 对象(我们学习过反射,都知道 Class
对象,在同一个 JVM 中,可以有很多的 Student 实例,但是 Student 的 Class 对象只有一个)。

因为是第一次执行,方法区中没有 Student 的 Class 对象,此时 JVM 就会调用类加载器(ClassLoader)。

类加载器有 2 大类:
第 1 种是虚拟机本身提供的,第 2 种是程序员自定义的(像 Tomcat 本身也有自己的类加载器)
类加载器(ClassLoader)要加载 Student 类的过程,就是要在物理位置找到 Student 类的字节码
文件(如 D:/workspace/web03/classes/Student.class)。
怎么才能找到?JVM 会根据 ClassPath 搜索。
当 JVM 找到 Student 类的字节码文件后,JVM 会将该字节码文件转换为一个 Student 的 Class 对
象,放入方法区
当这个 Student 的 Class 对象构造完毕,类加载过程就完成了。


第 2 步
将 Sutdent 类型的变量 s 放入栈(Stack)中;“ Student s = new Student();”

第 3 步
“ Student s = new Student();”在堆(heap)中创建一个 Student 对象,变量 s 指向该对象。

第 4 步
play()方法放在代码区中 Student 的 Class 对象中,对象的方法在 JVM 中只有 1 仹,对象的属性(每
对象都有独有的属性)可以有多仹。
执行“ s.play();” 方法时,Student 对象到方法区中找到 play()方法并执行。

第 5 步
执行“ Student s2 = new Student();”时,JVM 到方法区中找到了 Student 的 Class 对象,所以
JVM 丌再调用 ClassLoader 加载 Class 对象。
将直接在堆中创建。

原文地址:https://www.cnblogs.com/dondming/p/5152889.html