热加载--代码

入口类:

	public static void main(String[] args) {
		while (true) {
			try {
				FileClassLoader a = new FileClassLoader("E:\\workspace-nfjd\\testrealpath\\WebContent\\WEB-INF\\classes\\");
				Object foo = a.findClass("Foo").newInstance();
				Method m = foo.getClass().getMethod("sayHello", new Class[] {});
				m.invoke(foo, new Object[] {});
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

 自己的类加载器:

public class FileClassLoader extends ClassLoader {


	/**
	 * @param drive
	 */
	public FileClassLoader(String drive) {
		super();
		this.drive = drive;
	}

	public   String drive = "E:\\workspace-nfjd\\classLoader\\bin\\";
	public   String fileType = ".class";


	public Class findClass(String name) {
		byte[] data = loadClassData(name);
		return defineClass(name, data, 0, data.length);
	}

	public byte[] loadClassData(String name) {
		FileInputStream fis = null;
		byte[] data = null;
		try {
			fis = new FileInputStream(new File(drive + name + fileType));
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int ch = 0;
			while ((ch = fis.read()) != -1) {
				baos.write(ch);
			}
			data = baos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}
	/**
	 * @param string
	 */
	public void setPath(String string) {
		this.drive=string;
	}
}

 

测试类:

public class Foo {
	{
		System.out.println("212121s111");

	}

	public void sayHello() {
		System.out.println("hhh222");
	}
}

 

相当于是新建了个类加载器, 内存会浪费点,不过原先的加载器会被GC掉。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值