java自定义类装载器

​
package com;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

//用户自定义类装载器必须创建java.long.ClassLoader的子类实现loadClass方法
public class ClassLoadDevice extends ClassLoader {
	// 用于保存class文件的目录
	String basePath;
	public ClassLoadDevice(String basePath) {
		this.basePath = basePath;
	}

	// 虚拟机会为每个类装载器维护一张列表,列表中是已经被请求过的类型名字
	@Override
	protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
		Class<?> result;
		byte[] classData;
		// 此方法是最终不可重写
		// 传递被请求的类型的包名和类名全限名:如:com.Car,如果这个类加载器具有该标记的类全限名的类型,初始类装载器就会返会表示这个类型的Class实例
		result = findLoadedClass(name);
		if (result != null) {
			return result;
		}
		// 此方法通过系统类装载器[原始类装载器](查看系统类装载器是否与此二进制文件的类)此方法是最终不可重写
		try {
			result = super.findSystemClass(name);
			if (result != null) {
				return result;
			}
		} catch (ClassNotFoundException e) {

		}
		// 获取class文件的字节码存储到byte数组中
		classData = getTypeFromBasePath(name);
		if (classData == null) {
			System.out.println("ClassNotFounDException");
		}
		// 通过defineClass方法完成装载过程,即解析二进制数据到内部数据格式,并且创建一个Class对象
		result = defineClass(name, classData, 0, classData.length);
		if (result == null) {
			System.out.println("ClassFormatError");
		}
		if (resolve) {
			resolveClass(result);
		}
		return result;
	}

	private byte[] getTypeFromBasePath(String name) {
		FileInputStream fis;
		// String fileName= basePath+File.separatorChar+name.replace(".",
		// File.separatorChar+name);
		try {
			fis = new FileInputStream(basePath);
		} catch (FileNotFoundException e) {

			e.printStackTrace();
			return null;
		}
		BufferedInputStream buffer = new BufferedInputStream(fis);
		ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
		try {
			int c = buffer.read();
			while (c != -1) {
				byteOutput.write(c);
				c = buffer.read();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (buffer != null) {
					buffer.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return byteOutput.toByteArray();
	}
}


		ClassLoadDevice classLoadDevice = new ClassLoadDevice("E:\\123\\Car.class");
		Class<?> cl1 = classLoadDevice.loadClass("com.Car.class");
		System.out.println(cl1.getClassLoader());

​卸载动态加载的Class对象和装载器
		classLoadDevice =null;
		cl1 =null;
		o=null;
		System.gc();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值