jvm(四)自定义类加载器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qwkxq/article/details/56511671

通过继承ClassLoader类覆盖findClass方法来自定义类加载器:



import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader{

	public static void main(String[] args) throws Exception {
		MyClassLoader loader1 = new MyClassLoader();
		loader1.setClassPath("D:\\codePath\\classloader\\a\\");
		MyClassLoader loader2 = new MyClassLoader(loader1);
		loader2.setClassPath("D:\\codePath\\classloader\\b\\");
		Class<?> clazz = loader2.loadClass("LoadClass");
		clazz.newInstance();
	}
	
	public MyClassLoader(){
		super();
	}
	
	public MyClassLoader(ClassLoader loader){
		super(loader);
	}
	
	protected Class<?> findClass(String fullclassName) throws ClassNotFoundException {
		String classPath = this.classPath+fullclassName.replaceAll("\\.", "\\")+".class";
		//System.out.println(classPath);
		byte[] data = getClassData(classPath);
		if(data==null){
			return null;
		}
		return this.defineClass(fullclassName, data, 0, data.length);
	}
	
	private byte[] getClassData(String path){
		byte[] data = null;
		InputStream in = null;
		ByteArrayOutputStream arrayOut = null;
		try {
			in = new FileInputStream(path);
			arrayOut = new ByteArrayOutputStream();
			int ch = 0;
			while(-1!=(ch=in.read())){
				arrayOut.write(ch);
			}
			data = arrayOut.toByteArray();
		} catch (Exception e) {
			return null;
		} finally{
			try {
				if(in!=null)in.close();
				if(arrayOut!=null)arrayOut.close();
			} catch (Exception ex) {
				return null;
			}
		}
		return data;
	}
	private String classPath;
	public String getClassPath() {
		return classPath;
	}

	public void setClassPath(String classPath) {
		this.classPath = classPath;
	}
}

加载的类:

public class LoadClass {
	public static int v1 = 0;
	public LoadClass(){
		System.out.println("loader is : "+this.getClass().getClassLoader());
	}
}


猜你喜欢

转载自blog.csdn.net/qwkxq/article/details/56511671