xulingbo/xulingbo.github.io

第六章-深入分析ClassLoader工作机制

lightnine opened this issue · 0 comments

在如何实现自己的ClassLoader的加载自定义路径下的class文件,即6.6.1章节,代码如下:
`package code;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
@author benjamin
@Date 创建时间:2017年5月20日下午11:06:03
*/
public class PathClassLoader extends ClassLoader {
private String classPath;
public PathClassLoader(String classPath) {
this.classPath = classPath;
}

protected Class<?> findClass(String name) throws ClassNotFoundException {
	if (packageName.startsWith(name)) {
		byte[] classData = getData(name);
		if (classData == null) {
			throw new ClassNotFoundException();
		} else {
			return defineClass(name,classData, 0, classData.length);
		}
	} else {
		return super.loadClass(name);
	}
}

private byte[] getData(String name) {
	String path = name + File.separatorChar 
			+ name.replace('.', File.separatorChar) + ".class";
	System.out.println(path);
	try {
		InputStream is = new FileInputStream(path);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		byte[] buffer = new byte[2048];
		int num = 0;
		while ((num = is.read(buffer)) != -1) {
			stream.write(buffer, 0 , num);
		}
		if (is != null) {
			is.close();
		}
		return stream.toByteArray();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return null;
}

}
`
这里面出现了pachageName,请问是在哪里定义的,还是packageName是这里的classPath。还有能给出单元测试代码吗?