自定义ClassLoader

1.ClassLoader方法解析

1.1 loadClass

逻辑主要是首先委托父加载器加载,然后尝试自己加载。自己加载则调用的是 findClass 方法,所以这个方法是我们主要需要覆盖的方法。

    protected Class loadClass(String name, boolean resolve)
        throws ClassNotFoundException
    {
        synchronized (getClassLoadingLock(name)) { //加锁,保证同一个类只有一条线程加载
            // First, check if the class has already been loaded
            Class c = findLoadedClass(name); //确认是否已被加载
            if (c == null) {
                long t0 = System.nanoTime();
                try {
                    if (parent != null) {
                        c = parent.loadClass(name, false); //父加载器尝试加载
                    } else {
                        c = findBootstrapClassOrNull(name);
                    }
                } catch (ClassNotFoundException e) {
                    // ClassNotFoundException thrown if class not found
                    // from the non-null parent class loader
                }

                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) {
                resolveClass(c); //对class进行解析
            }
            return c;
        }
    }

1.2 findClass

默认情况下,ClassLoader直接抛出异常,也就是自定义类加载器必须重写该方法。

    protected Class findClass(String name) throws ClassNotFoundException {
        throw new ClassNotFoundException(name); 
    }

2.自定义ClassLoader

下面我会自定义类加载器,加载类路径下的class文件。因此会存在同一份class文件被两个ClassLoader加载的情况。

2.1 MyClassLoader

package org.ljf.classld;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;

public class MyClassLoader extends ClassLoader {
	
	private static MyClassLoader instance = new MyClassLoader();
	
	public static MyClassLoader getMyClassLoader() {
		return instance;
	}

	private MyClassLoader() {
		//把AppClassLoader作为父类加载器
		super(ClassLoader.getSystemClassLoader());
	}
	
	@Override
	protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
		if (name.equals("org.ljf.classld.Clock")) { //防止委派加载这个类
			return findClass(name);
		}
		return super.loadClass(name, resolve);
	}
	
	@Override
	protected Class findClass(String name) throws ClassNotFoundException {
		BufferedInputStream bis = null;
		try {
			//加载类路径下的类
			URL url = ClassLoader.getSystemClassLoader().getResource("");
			String path = url.getPath();
			if (path.endsWith("/")) {
				path = path.substring(0, path.length() - 1);
			}
			String packagePath = name.replaceAll("\\.", "/");
			path = path + "/" + packagePath + ".class";
			bis = new BufferedInputStream(new FileInputStream(path));
			byte[] data = new byte[bis.available()];
			bis.read(data);
			return defineClass(name, data, 0, data.length);
		} catch (Exception e) {
			e.printStackTrace();
			return super.findClass(name);
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}

2.2 Clock 一个被加载的普通类

package org.ljf.classld;

public class Clock {
}

2.3 测试

package org.ljf.classld;


public class Tester {
	public static void main(String[] args) {
		try {
			Class systemClazz = Class.forName("org.ljf.classld.Clock", true, ClassLoader.getSystemClassLoader());
			Class myClazz = Class.forName("org.ljf.classld.Clock", true, MyClassLoader.getMyClassLoader());
			System.out.println("systemClazz == myClazz ? " + (systemClazz == myClazz));
			Object obj = systemClazz.newInstance();
			System.out.println("obj is instanceOf systemClazz : " + systemClazz.isInstance(obj));
			System.out.println("obj is instanceOf myClazz : " + myClazz.isInstance(obj));
			Clock clock = (Clock) obj;
			System.out.println("clock 's classLoader : " + clock.getClass().getClassLoader());
			Clock clock2 = (Clock)myClazz.newInstance(); //抛异常,因为jvm默认用AppClassLoader加载Clock,所以这里强转出错
			System.out.println(clock2.getClass().getClassLoader());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

输出:

自定义ClassLoader_第1张图片

你可能感兴趣的:(Java基础)