这些是以前看JVM规范时候做的笔记,也不算笔记就是抄的原文. 做Android开发用java开发应用,必然需要了解java中的类的生命周期,这样才能在碰到问题的时候大概的清楚是怎么回事,知其然,并且知其所以然.
在Java虚拟机中一个java类从文件加载到到内存生成对象到虚拟机销毁这个java对象总共要经过: 加载,链接,初始化,使用,卸载这五个步骤. 其中链接部分又可以分为:验证,准备,解析三个子步骤.
从JAVA虚拟机规范中我们能够了解到类的加载过程和加载原理,并且知道在每个过程中都发生了哪些事情,可能会发生哪些异常(对定位线上问题非常有帮助).
jvms8 $5.3
Loading is the process of finding the binary representation of a class or interface type with a particular name and creating a class or interface from that binary representation.
jvms8 $5.4
Linking is the process of taking a class or interface and combining it into the run-time state of the Java Virtual Machine so that it can be executed.
0x01. 验证(Verification)
Verification (§4.10) ensures that the binary representation of a class or interface is structurally correct (§4.9). Verification may cause additional classes and interfaces to be loaded (§5.3) but need not cause them to be verified or prepared. If the binary representation of a class or interface does not satisfy the static or structural constraints listed in §4.9, then a VerifyError must be thrown at the point in the program that caused the class or interface to be verified. If an attempt by the Java Virtual Machine to verify a class or interface fails because an error is thrown that is an instance of LinkageError (or a subclass), then subsequent attempts to verify the class or interface always fail with the same error that was thrown as a result of the initial verification attempt.
0x02. 准备(Preparation)
Preparation involves creating the static fields for a class or interface and initializing such fields to their default values (§2.3, §2.4). This does not require the execution of any Java Virtual Machine code; explicit initializers for static fields are executed as part of initialization (§5.5), not preparation.
0x03. 解析(Resolution)
The Java Virtual Machine instructions anewarray, checkcast, getfield, getstatic, instanceof, invokedynamic, invokeinterface, invokespecial, invokestatic, invokevirtual, ldc, ldc_w, multianewarray, new, putfield, and putstatic make symbolic references to the run-time constant pool. Execution of any of these instructions requires resolution of its symbolic reference. Resolution is the process of dynamically determining concrete values from symbolic references in the run-time constant pool.
Initialization of a class or interface consists of executing the class or interface initialization method
这个就不用多说了,谁用谁知道.
当这个类的对象被虚拟机回收掉以后,则这个类的生命周期结束.