Java类加载过程
装载:通过类的全限定名获取二进制字节流,将二进制字节流转换成方法区中的运行时数据结构,在内存中生成Java.lang.class对象
链接:执行下面的验证、准备和解析步骤,其中解析步骤是可以选择的;
验证:检查导入类或接口的二进制数据的正确性;(文件格式验证,元数据验证,字节码验证,符号引用验证)
准备:给类的静态变量分配并初始化存储空间(此时初始化的是类型的初始值,还没有到代码中设定的初值)
解析:将常量池中的符号引用转成直接引用;
初始化:激活类的静态变量的初始化Java代码和静态Java代码块,并初始化程序员设置的变量值。
在java中Class.forName()和ClassLoader都可以对类进行加载。ClassLoader就是遵循双亲委派模型最终调用启动类加载器的类加载器,实现的功能是“通过一个类的全限定名来获取描述此类的二进制字节流”,获取到二进制流后放到JVM中。Class.forName()方法实际上也是调用的CLassLoader来实现的。
Class.forName()的源码如下:
/**
* Returns the {@code Class} object associated with the class or
* interface with the given string name. Invoking this method is
* equivalent to:
*
* <blockquote>
* {@code Class.forName(className, true, currentLoader)}
* </blockquote>
***省略部分注释
**/
@CallerSensitive
public static Class<?> forName(String className)
throws ClassNotFoundException {
Class<?> caller = Reflection.getCallerClass();
return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
}
最后调用的方法是forName0这个方法,在这个forName0方法中的第二个参数被默认设置为了true,这个参数代表是否对加载的类进行初始化,设置为true时会类进行初始化,代表会执行类中的静态代码块,以及对静态变量的赋值等操作。从注释中可知等价于Class.forName(className, true, currentLoader)
/**
* Returns the {@code Class} object associated with the class or
* interface with the given string name, using the given class loader.
* Given the fully qualified name for a class or interface (in the same
* format returned by {@code getName}) this method attempts to
* locate, load, and link the class or interface. The specified class
* loader is used to load the class or interface. If the parameter
* {@code loader} is null, the class is loaded through the bootstrap
* class loader. The class is initialized only if the
* {@code initialize} parameter is {@code true} and if it has
* not been initialized earlier.
*
* <p> If {@code name} denotes a primitive type or void, an attempt
* will be made to locate a user-defined class in the unnamed package whose
* name is {@code name}. Therefore, this method cannot be used to
* obtain any of the {@code Class} objects representing primitive
* types or void.
*
* <p> If {@code name} denotes an array class, the component type of
* the array class is loaded but not initialized.
*
* <p> For example, in an instance method the expression:
*
* <blockquote>
* {@code Class.forName("Foo")}
* </blockquote>
*
* is equivalent to:
*
* <blockquote>
* {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
* </blockquote>
*
* Note that this method throws errors related to loading, linking or
* initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
* Java Language Specification</em>.
* Note that this method does not check whether the requested class
* is accessible to its caller.
*
* <p> If the {@code loader} is {@code null}, and a security
* manager is present, and the caller's class loader is not null, then this
* method calls the security manager's {@code checkPermission} method
* with a {@code RuntimePermission("getClassLoader")} permission to
* ensure it's ok to access the bootstrap class loader.
*
* @param name fully qualified name of the desired class
* @param initialize if {@code true} the class will be initialized.
* See Section 12.4 of <em>The Java Language Specification</em>.
* @param loader class loader from which the class must be loaded
* @return class object representing the desired class
*
* @exception LinkageError if the linkage fails
* @exception ExceptionInInitializerError if the initialization provoked
* by this method fails
* @exception ClassNotFoundException if the class cannot be located by
* the specified class loader
*
* @see java.lang.Class#forName(String)
* @see java.lang.ClassLoader
* @since 1.2
*/
@CallerSensitive
public static Class<?> forName(String name, boolean initialize,
ClassLoader loader)
throws ClassNotFoundException
{
Class<?> caller = null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// Reflective call to get caller class is only needed if a security manager
// is present. Avoid the overhead of making this call otherwise.
caller = Reflection.getCallerClass();
if (sun.misc.VM.isSystemDomainLoader(loader)) {
ClassLoader ccl = ClassLoader.getClassLoader(caller);
if (!sun.misc.VM.isSystemDomainLoader(ccl)) {
sm.checkPermission(
SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
}
}
return forName0(name, initialize, loader, caller);
}
解释:
(1)尝试定位、加载 和链接
(2)如果给定的loader为null,会使用 bootstrap class loader加载类
(3)只有参数 initialize 为 true 并且这个类之前没有被初始化才会进行类的初始化
(4)如果name代表原始类型或void,将尝试在未命名包中查找名为{@code name}的用户定义类。因此,此方法不能用于获取任何表示原始类型或者void的class对象
(5)如果name代表数组类型,数组的组件类型会被加载,但是不会被初始化。(这一点?)
下面举例说明:
首先定义一个User类,代码如下
package com.Ycb.classloader;
public class User {
static {
System.out.println("执行了User的static代码块!");
}
}
示列一、调用Class.forName(String name)方法
package com.Ycb.classloader;
public class ClassLoaderTest {
public static void main(String[] args) {
try {
Class<User> clazz = (Class<User>) Class.forName("com.Ycb.classloader.User");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
运行结果:
执行了User的static代码块!
实例二:调用 forName(String name, boolean initialize, ClassLoader loader)
package com.Ycb.classloader;
public class ClassLoaderTest {
public static void main(String[] args) {
try {
Class<User> clazz = (Class<User>) Class.forName("com.Ycb.classloader.User", false, ClassLoader.getSystemClassLoader());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
运行结果:如果initialize为false,静态代码块就不会执行,不会输出User中的静态代码块的内容
实例三:使用ClassLoader的测试方法:
首先介绍下ClassLoader.loadClass的源码
public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
内部默认调用 Class<?> loadClass(String name, false);
第2个 boolean参数,表示目标对象是否进行链接,false表示不进行链接,由上面介绍可以,不进行链接意味着不进行包括初始化等一些列步骤,那么静态块和静态对象就不会得到执行
下面演示例子:
package com.Ycb.classloader;
public class ClassLoaderTest {
public static void main(String[] args) {
try {
ClassLoader.getSystemClassLoader().loadClass("com.Ycb.classloader.User");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
不会输出User中的static代码块,根据运行结果得出Class.forName加载类时将类进了初始化,而ClassLoader的loadClass并没有对类进行初始化,只是把类加载到了虚拟机中。
应用场景
在我们熟悉的Spring框架中的IOC的实现就是使用的ClassLoader。
而在我们使用JDBC时通常是使用Class.forName()方法来加载数据库连接驱动。这是因为在JDBC规范中明确要求Driver(数据库驱动)类必须向DriverManager注册自己。
以MySQL的驱动为例解释:
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
//省略部分代码
//
// Register ourselves with the DriverManager
//
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
//省略部分代码
}
个人记录,有误盼指出,感谢!