Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lightnine opened this issue May 20, 2017 · 0 comments
Open

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

lightnine opened this issue May 20, 2017 · 0 comments

Comments

@lightnine
Copy link

在如何实现自己的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。还有能给出单元测试代码吗?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant