接着上篇博客,下面我们来看看如何自定义类加载器
自定义类加载器
JVM中除根类加载器之外的所有类加载器都是ClassLoader子类的实例,开发者可以通过扩展ClassLoader的子类,并重写该ClassLoader所包含的方法来实现自定义的类加载器。
ClassLoader类有如下两个关键方法:
- loadClass(String name, boolean resolve): 该方法为ClassLoader的入口点,根据指定名称来加载类,系统就是调用ClassLoader的该方法来获取指定类对应的Class对象。
- findClass(String name): 根据指定名称来查找类。
/**
* Loads the class with the specified <a href="#name">binary name</a>. The
* default implementation of this method searches for classes in the
* following order:
*
* <ol>
*
* <li><p> Invoke {@link #findLoadedClass(String)} to check if the class
* has already been loaded. </p></li>
*
* <li><p> Invoke the {@link #loadClass(String) <tt>loadClass</tt>} method
* on the parent class loader. If the parent is <tt>null</tt> the class
* loader built-in to the virtual machine is used, instead. </p></li>
*
* <li><p> Invoke the {@link #findClass(String)} method to find the
* class. </p></li>
*
* </ol>
*
* <p> If the class was found using the above steps, and the
* <tt>resolve</tt> flag is true, this method will then invoke the {@link
* #resolveClass(Class)} method on the resulting <tt>Class</tt> object.
*
* <p> Subclasses of <tt>ClassLoader</tt> are encouraged to override {@link
* #findClass(String)}, rather than this method. </p>
*
* <p> Unless overridden, this method synchronizes on the result of
* {@link #getClassLoadingLock <tt>getClassLoadingLock</tt>} method
* during the entire class loading process.
*
* @param name
* The <a href="#name">binary name</a> of the class
*
* @param resolve
* If <tt>true</tt> then resolve the class
*
* @return The resulting <tt>Class</tt> object
*
* @throws ClassNotFoundException
* If the class could not be found
*
*
* 加载指定的<a href="#name">二进制名</a>的类
* 此方法查找class的默认实现有有以下几点:
* 1、调用findLoadedClass(String)检查该Class是否已加载
* 2、调用父类加载器的loadClass(String)方法;如果父类加载器为null,使用虚拟机内置的loader
* 3、调用findClass(String)方法去查找该Class
*
* 如果使用上述步骤找到该Class,且resolve是true,则调用resolveClass(Class),将结果返回;
* ClassLoader的子类鼓励重写findClass(String),而不是这个方法
*
* 除非被重写,否则此方法在整个类加载过程中会对结果进行同步getClassLoadingLock
*
*
*/
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
/**
* 除非被重写,否则此方法在整个类加载过程中会对结果进行同步getClassLoadingLock
*/
synchronized (getClassLoadingLock(name)) {
// First, check if the class has already been loaded(第一,检查该Class是否已加载)
Class<?> c = findLoadedClass(name);
if (c == null) {
long t0 = System.nanoTime();
try {
if (parent != null) {
/**
* 调用父类加载器的loadClass(String)方法
*/
c = parent.loadClass(name, false);
} else {
/**
* 如果父类加载器为null,使用虚拟机内置的loader
* (BootstrapClassLoader,JVM实现,底层是native方法)
*/
c = findBootstrapClassOrNull(name);
}
} catch (ClassNotFoundException e) {
// ClassNotFoundException thrown if class not found
// from the non-null parent class loader
}
/**
* 以上步骤没找到class的话
* 调用findClass(String)方法去查找该Class
*/
if (c == null) {
// If still not found, then invoke findClass in order
// to find the class.
long t1 = System.nanoTime();
c = findClass(name);
// this is the defining class loader; record the stats
sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
sun.misc.PerfCounter.getFindClasses().increment();
}
}
if (resolve) {
// JVM实现,底层是native方法,如果c为null会抛NullPointException异常
resolveClass(c);
}
return c;
}
}
/**
* Links the specified class. This (misleadingly named) method may be
* used by a class loader to link a class. If the class <tt>c</tt> has
* already been linked, then this method simply returns. Otherwise, the
* class is linked as described in the "Execution" chapter of
* <cite>The Java™ Language Specification</cite>.
*
* @param c
* The class to link
*
* @throws NullPointerException
* If <tt>c</tt> is <tt>null</tt>.
*
* @see #defineClass(String, byte[], int, int)
*
*
* 链接指定的类。这个(容易引起误解的命名)方法可能是被类加载器用来链接类的。如果类c已链接,则此方法直接返回。否则,进行链接
*/
protected final void resolveClass(Class<?> c) {
// native方法,java源码中方法以0结尾的一般都是native方法(例如Thread类的start()方法对应的start0()方法),需要JVM去调用C/C++去执行
resolveClass0(c);
}
/**
* Finds the class with the specified <a href="#name">binary name</a>.
* This method should be overridden by class loader implementations that
* follow the delegation model for loading classes, and will be invoked by
* the {@link #loadClass <tt>loadClass</tt>} method after checking the
* parent class loader for the requested class. The default implementation
* throws a <tt>ClassNotFoundException</tt>.
*
* @param name
* The <a href="#name">binary name</a> of the class
*
* @return The resulting <tt>Class</tt> object
*
* @throws ClassNotFoundException
* If the class could not be found
*
* @since 1.2
*
* 加载指定的<a href="#name">二进制名</a>的类
* 类加载器实现应该重写此方法使用委托模型加载类,
* 将在loadClass(String name, boolean resolve)方法检查父类加载后调用该该方法
* 默认实现抛出一个ClassNotFoundException异常
*/
protected Class<?> findClass(String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}
如果需要实现自定义的ClassLoader,可以通过重写以上两个方法来实现。从源码中也可以看出,通常推荐重写findClass()方法,而不是loadClass()方法。
从源码中可以看出,重写findClass()方法可以避免覆盖默认类加载器的父类委托、缓存机制两种策略;如果重写loadClass()方法,实现逻辑更复杂。
我们来看看ClassLoader的源码:
/**
* Converts an array of bytes into an instance of class <tt>Class</tt>,
* with an optional <tt>ProtectionDomain</tt>. If the domain is
* <tt>null</tt>, then a default domain will be assigned to the class as
* specified in the documentation for {@link #defineClass(String, byte[],
* int, int)}. Before the class can be used it must be resolved.
*
* 将字节数组转换为Class实例,
* *带有一个可选的<tt>ProtectionDomain</tt>。如果定义域是null,则将一个默认域赋给该class,
* 该默认域需要在defineClass(String, byte[],int, int)文档中指定。在使用Class之前,必须解析
*
* <p> The first class defined in a package determines the exact set of
* certificates that all subsequent classes defined in that package must
* contain. The set of certificates for a class is obtained from the
* {@link java.security.CodeSource <tt>CodeSource</tt>} within the
* <tt>ProtectionDomain</tt> of the class. Any classes added to that
* package must contain the same set of certificates or a
* <tt>SecurityException</tt> will be thrown. Note that if
* <tt>name</tt> is <tt>null</tt>, this check is not performed.
* You should always pass in the <a href="#name">binary name</a> of the
* class you are defining as well as the bytes. This ensures that the
* class you are defining is indeed the class you think it is.
*
* 作为限定包中定义的第一个类,该包中定义的所有后续类必须包含精确的证书。
* 类的证书集从ProtectionDomain内的java.security.CodeSource 的CodeSource()中.
* 任何Class都可以添加到该包中必须包含同一套证书或者会抛SecurityException异常。
* 注意,如果name为null,此检查不执行。您应该始终传入<a href="#name">二进制名</a>
* 类和字节一起定义。这确保了你定义的类确实是你认为的类。
*
* <p> The specified <tt>name</tt> cannot begin with "<tt>java.</tt>", since
* all classes in the "<tt>java.*</tt> packages can only be defined by the
* bootstrap class loader. If <tt>name</tt> is not <tt>null</tt>, it
* must be equal to the <a href="#name">binary name</a> of the class
* specified by the byte array "<tt>b</tt>", otherwise a {@link
* NoClassDefFoundError <tt>NoClassDefFoundError</tt>} will be thrown. </p>
*
*指定的name不能以java.开头,以java.开头的Class只能由根类加载器加载。
* 如果name不为null,则必须等于由字节数组b指定类的二进制名,否则抛出oClassDefFoundError错误
*
*
* @param name
* The expected <a href="#name">binary name</a> of the class, or
* <tt>null</tt> if not known
*
* @param b
* The bytes that make up the class data. The bytes in positions
* <tt>off</tt> through <tt>off+len-1</tt> should have the format
* of a valid class file as defined by
* <cite>The Java™ Virtual Machine Specification</cite>.
* 该数组的范围为[off,off+len-1]
*
* @param off
* The start offset in <tt>b</tt> of the class data
*
* @param len
* The length of the class data
*
* @param protectionDomain
* The ProtectionDomain of the class
*
* @return The <tt>Class</tt> object created from the data,
* and optional <tt>ProtectionDomain</tt>.
*
* @throws ClassFormatError
* If the data did not contain a valid class
*
* @throws NoClassDefFoundError
* If <tt>name</tt> is not equal to the <a href="#name">binary
* name</a> of the class specified by <tt>b</tt>
*
* @throws IndexOutOfBoundsException
* If either <tt>off</tt> or <tt>len</tt> is negative, or if
* <tt>off+len</tt> is greater than <tt>b.length</tt>.
*
* @throws SecurityException
* If an attempt is made to add this class to a package that
* contains classes that were signed by a different set of
* certificates than this class, or if <tt>name</tt> begins with
* "<tt>java.</tt>".
*/
protected final Class<?> defineClass(String name, byte[] b, int off, int len,
ProtectionDomain protectionDomain)
throws ClassFormatError
{
protectionDomain = preDefineClass(name, protectionDomain);
String source = defineClassSourceLocation(protectionDomain);
Class<?> c = defineClass1(name, b, off, len, protectionDomain, source);
postDefineClass(c, protectionDomain);
return c;
}
在ClassLoader里还有一个核心方法Class<?> defineClass(String name, byte[] b, int off, int len),该方法负责将指定类的字节码文件(即Class文件,如Hello.class)读入字节数组byte[] b中,并把它转换为Class对象,该字节码可以来源于文件、网络等。
defineClass()方法管理JVM的许多复杂实现,它负责将字节码分析成运行时数据结构,并校验有效。该方法时final类型,无法重写。
除此之外,ClassLoader里还包含一些普通方法:
- findSystemClass(String name): 从本地文件系统装入文件,它在本地文件系统中寻找类文件,如果存在,就是要defineClass()方法将原始字节转换成Class对象,将文件转换成类。
/**
* Finds a class with the specified <a href="#name">binary name</a>,
* loading it if necessary.
*
* <p> This method loads the class through the system class loader (see
* {@link #getSystemClassLoader()}). The <tt>Class</tt> object returned
* might have more than one <tt>ClassLoader</tt> associated with it.
* Subclasses of <tt>ClassLoader</tt> need not usually invoke this method,
* because most class loaders need to override just {@link
* #findClass(String)}. </p>
*
* @param name
* The <a href="#name">binary name</a> of the class
*
* @return The <tt>Class</tt> object for the specified <tt>name</tt>
*
* @throws ClassNotFoundException
* If the class could not be found
*
* @see #ClassLoader(ClassLoader)
* @see #getParent()
*/
protected final Class<?> findSystemClass(String name)
throws ClassNotFoundException
{
ClassLoader system = getSystemClassLoader();
if (system == null) {
if (!checkName(name))
throw new ClassNotFoundException(name);
Class<?> cls = findBootstrapClass(name);
if (cls == null) {
throw new ClassNotFoundException(name);
}
return cls;
}
return system.loadClass(name);
}
- static getSystemClassLoader(): 这是一个静态方法
/**
* Find a resource of the specified name from the search path used to load
* classes. This method locates the resource through the system class
* loader (see {@link #getSystemClassLoader()}).
*
* @param name
* The resource name
*
* @return A {@link java.net.URL <tt>URL</tt>} object for reading the
* resource, or <tt>null</tt> if the resource could not be found
*
* @since 1.1
*/
public static URL getSystemResource(String name) {
ClassLoader system = getSystemClassLoader();
if (system == null) {
return getBootstrapResource(name);
}
return system.getResource(name);
}
- getParent():获取该类的父类加载器
/**
* Returns the parent class loader for delegation. Some implementations may
* use <tt>null</tt> to represent the bootstrap class loader. This method
* will return <tt>null</tt> in such implementations if this class loader's
* parent is the bootstrap class loader.
*
* <p> If a security manager is present, and the invoker's class loader is
* not <tt>null</tt> and is not an ancestor of this class loader, then this
* method invokes the security manager's {@link
* SecurityManager#checkPermission(java.security.Permission)
* <tt>checkPermission</tt>} method with a {@link
* RuntimePermission#RuntimePermission(String)
* <tt>RuntimePermission("getClassLoader")</tt>} permission to verify
* access to the parent class loader is permitted. If not, a
* <tt>SecurityException</tt> will be thrown. </p>
*
* @return The parent <tt>ClassLoader</tt>
*
* @throws SecurityException
* If a security manager exists and its <tt>checkPermission</tt>
* method doesn't allow access to this class loader's parent class
* loader.
*
* @since 1.2
*/
@CallerSensitive
public final ClassLoader getParent() {
if (parent == null)
return null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// Check access to the parent class loader
// If the caller's class loader is same as this class loader,
// permission check is performed.
checkClassLoaderPermission(parent, Reflection.getCallerClass());
}
return parent;
}
- resolveClass(Class<?> c): 链接指定的类。类加载器可以使用此方法来链接类c
- findLoadedClass(String name): 如果此Java虚拟机已经加载了名为name的类,则直接返回该类对应的Class实例,否则返回null。该方法是Java类加载缓存机制的体现。
/**
* Returns the class with the given <a href="#name">binary name</a> if this
* loader has been recorded by the Java virtual machine as an initiating
* loader of a class with that <a href="#name">binary name</a>. Otherwise
* <tt>null</tt> is returned.
*
* @param name
* The <a href="#name">binary name</a> of the class
*
* @return The <tt>Class</tt> object, or <tt>null</tt> if the class has
* not been loaded
*
* @since 1.1
*/
protected final Class<?> findLoadedClass(String name) {
if (!checkName(name))
return null;
return findLoadedClass0(name);
}
下面自定义类加载器,该ClassLoader通过重写findClass()方法来实现自定义的类加载机制。这个ClassLoader可以在类加载之前先编译该类的源文件,从而实现运行Java之前先编译该程序的目标,这样即可通过该ClassLoader直接运行Java源文件。
// package cn.crazy.load;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* @ProjectName: Java
* @Package: cn.crazy.load
* @ClassName: MyClassLoader
* @Author: zhangli
* @Description: 自定义类加载器
* @Date: 2020/5/30 16:12
* @Version: 1.0
*/
public class MyClassLoader extends ClassLoader{
/**
* 读取一个文件的内容
* @param fileName
* @return
* @throws Exception
*/
private byte[] getBytes(String fileName) throws Exception{
File file = new File(fileName);
long length = file.length();
byte[] buffer = new byte[(int) length];
FileInputStream inputStream = new FileInputStream(file);
/**
* 一次性读取Class文件的全部二进制数据
*/
int len = inputStream.read(buffer);
if(len != length){
throw new IOException("无法读取全部文件[读取长度:" + len + ", 文件长度:" + length + "]");
}
return buffer;
}
/**
* 编译指定的Java文件
* @param javaFile
* @return
* @throws Exception
*/
private boolean compile(String javaFile) throws Exception{
System.out.println("MyClassLoader正在编译"+ javaFile + "……");
/**
* 调用系统的javac命令
*/
Process process = Runtime.getRuntime().exec("javac -encoding UTF-8 " + javaFile);
System.out.println("调用系统的javac命令");
try {
/**
* 其他线程都等待这个线程完成
*/
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("其他线程都等待这个线程完成");
/**
* 获取线程的退出值(0表示正常终止)
*/
int value = process.exitValue();
/**
* 编译是否成功
*/
if(value == 0){
System.out.println("编译成功");
}
return value == 0;
}
/**
* 重写ClassLoader的findClass()方法
* @param name
* @return
* @throws ClassNotFoundException
*/
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
Class<?> clazz = null;
/**
* 将包路径中的.替换成/
*/
String filePath = name.replace(".", "/");
System.out.println("filePath = " + filePath);
String javaFileName = filePath + ".java";
String classFileName = filePath + ".class";
/**
* 加载文件
*/
File javaFile = new File(javaFileName);
File classFile = new File(classFileName);
/**
* 当指定java源文件存在,且Class文件不存在
* 或者
* java源文件的修改时间比Class文件的修改时间更晚,需要重新编译
*/
if((javaFile.exists() && !classFile.exists()) || (javaFile.lastModified() > classFile.lastModified())){
try {
/**
* 如果编译失败或者该Class文件不存在,抛出ClassNotFoundException
*/
if(!compile(javaFileName) || !classFile.exists()){
throw new ClassNotFoundException("ClassNotFoundException:" + javaFileName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 如果Class文件存在,将该文件转换成Class对象
*/
if(classFile.exists()){
try {
// 将Class文件的二进制数据转换成数组
byte[] bytes = getBytes(classFileName);
/**
* 调用ClassLoader的defineClass()方法将二进制数据转换成Class对象
*/
clazz = defineClass(name, bytes, 0, bytes.length);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 加载失败,抛出ClassNotFoundException
*/
if(clazz == null){
throw new ClassNotFoundException(name);
}
return clazz;
}
public static void main(String[] args) throws Exception {
/**
* 如果运行该程序时没有参数,即没有目标类
*/
if(args.length < 1){
System.out.println("缺少目标类,请按如下格式输入Java源文件: ");
System.out.println("java MyClassLoader ClassName");
}
/**
* cn.crazy.load.MyClassLoader cn.crazy.load.ClassLoadingTest
* src/cn/crazy/load/MyClassLoader.java
*
*
*/
/**
* 第一个参数是需要运行的类
*/
String runClass = args[0];
/**
* 剩下的参数作为运行目标类时的参数
*/
String[] runArgs = new String[args.length -1];
System.arraycopy(args, 1, runArgs, 0, runArgs.length);
MyClassLoader myClassLoader = new MyClassLoader();
Class<?> clazz = myClassLoader.loadClass(runClass);
/**
* 获取需要运行的类的main()方法
*/
Method main = clazz.getMethod("main", (new String[0]).getClass());
Object[] argsArr = {runArgs};
main.invoke(null,argsArr);
}
}
// package cn.crazy.load;
/**
* @ProjectName: Java
* @Package: cn.crazy.load
* @ClassName: ClassLoadingTest
* @Author: zhangli
* @Description: 类加载测试
* @Date: 2020/5/31 16:56
* @Version: 1.0
*/
public class ClassLoadingTest {
public static void main(String[] args) {
for(String arg : args){
System.out.println("运行参数:" + arg);
}
}
}
运行:cmd命令要进入MyClassLoader.java路径下,记得将包名注释掉,否则会报“无法加载主类”的错误。
MyClassLoader.java是要进行编译的,编译时最好指定编码格式,预防中文乱码错误。
cmd输入:
javac -encoding UTF-8 MyClassLoader.java
java MyClassLoader ClassLoadingTest zhangli test 测试
从上面的运行结果可以看出无须编译ClassLoadingTest.java,直接通过java MyClassLoader ClassLoadingTest命令运行即可。
实际上,使用自定义的类加载器可以实现更多复杂的功能,比如:
- 执行代码前自动验证数字签名
- 根据用户提供的密码解密代码,从而实现代码混淆器来避免反编译*.class文件
- 根据用户需求动态的加载类
- 根据应用需求把其他数据以字节码的方式加载到应用中
URLClassLoader类
Java为ClassLoader提供了一个URLClassLoader实现类。该类也是系统类加载器和扩展类加载器的父类(此处的父类,就是指类与类之间的继承关系)。URLClassLoader功能比较强大,它既可以从本地文件系统获取二进制文件来加载类,也可以从远程主机获取二进制文件类加载类。
在应用程序中可以直接使用URLClassLoader加载类,URLClassLoader类提供了如下两个构造器。
- URLClassLoader(URL[] urls): 使用 默认的父类类加载器创建一个ClassLoader对象 ,该对象 从urls所指定的系统路径来查询并加载类
- URLClassLoader(URL[] urls, ClassLoader parent): 使用指定 的父类加载器创建一个ClassLoader对象,其他功能与前一个构造器相同。
一旦得到了URLClassLoader对象之后,就可以调用该对象的loadClass()方法类加载指定类。
下面程序 示范了如何直接从文件系统中加载MySQL驱动,并使用该驱动来获取数据库连接。通过这种方式来获取数据库连接,无须将MySQL驱动添加到CLASSPATH环境变量中。
public class URLClassLoaderTest {
/**
* sql连接对象
*/
private static Connection connection;
/**
* 获取sql连接对象
*/
public static Connection getConnection(String url, String username, String password) throws Exception{
if(connection == null){
/**
* mysql-connector-java-5.1.37.jar放在当前java文件路径下
* file: 表示本地文件加载
*/
URL[] urls = {new URL("file:mysql-connector-java-5.1.37.jar")};
URLClassLoader loader = new URLClassLoader(urls);
Driver driver = (Driver) loader.loadClass("com.mysql.jdbc.Driver").newInstance();
/**
* 创建一个设置jdbc连接的Properties对象
*/
Properties properties = new Properties();
properties.setProperty("user", username);
properties.setProperty("password", password);
/**
* 调用Driver对象的connect方法取得数据库连接
*/
connection = driver.connect(url, properties);
}
return connection;
}
public static void main(String[] args) throws Exception{
Connection connection = getConnection("jdbc:mysql://localhost:3306/mysql", "root", "123456");
/**
* 拿到connection进行数据库操作
* ……
*/
}
}
上面的程序创建了一个URLClassLoader对象,该对象使用默认父类加载器,该类加载器的类加载路径是当前路径下的mysql-connector-java-5.1.37.jar文件。创建URLClassLoader时传入一个URL数组参数,该ClassLoader就可以从该URL数组中加载指定类,这里的URL以file:为前缀,表明从本地文件系统加载;可以以http:为前缀,表明从互联网通过HTTP访问加载;可以以ftp:为前缀,表明从互联网通过FTP访问来加载……功能非常强大。