《黑马程序员》类加载器及其委托机制的深入研究

类加载器

 

BootStrap(jre/lib/rt.jar ) 、 ExtClassLoader(jre/lib/ext/*.jar) 、 AppClassloader(classPath指定的所有jar包及其class类)

虚拟机默认自动加载BootStrap 然后按照类加载继承树一次往下加载每个加载器。 类加载器的原理是委托机制,一次往上类推,如果上面成功加载,则下面的加载器就不在加载。如果从上往下都没有加载成功。自己加载也没有成功,则返回classNoFound异常

自定义类加载器:

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MyLoader extends ClassLoader {

	public static void main(String args[]) throws IOException {
		ClassLoader loader = MyLoader.class.getClassLoader();
		while (loader != null) {
			System.out.println(loader);
			loader = loader.getParent();
		}
		String[] ss ={new String("E:\\javaweb\\enhanceHigh\\bin\\Test.class"),new String("class")};
		setClass(ss);

	}

	private static void setClass(String[] args) throws FileNotFoundException,
			IOException {
		String srcPath = args[0];
		String destDir = args[1];
		FileInputStream in = new FileInputStream(srcPath);

		String destPath = destDir + "\\"
				+ srcPath.substring(srcPath.lastIndexOf('\\') + 1);

		FileOutputStream out = new FileOutputStream(destPath);
		cypher(in, out);
		in.close();
		out.close();
	}

	@SuppressWarnings("deprecation")
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		// TODO Auto-generated method stub
		String classFileName=classDir+"\\"+name+".class";
		try {
			FileInputStream fis=new FileInputStream(classFileName);
			ByteArrayOutputStream bos=new ByteArrayOutputStream();
			cypher(fis, bos);
			byte[] by=bos.toByteArray();
			return defineClass(by, 0, by.length);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return super.findClass(name);
	}
/**
 * 数据加密类
 * @param in
 * @param out
 * @throws IOException
 */
	public static void cypher(InputStream in, OutputStream out)
			throws IOException {
		int b = -1;
		while ((b = in.read()) != -1) {

			out.write(b ^ 0xff);

		}
	}
	private String classDir;
	public MyLoader(String classDir){
		this.classDir=classDir;
	}
}


注意:自己的类加载时,一定要确保父类加载器中没有此类,否则父类加载了,子类就加在不上了。这里是模板模式 !

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值