0%

自定义类加载器-1

文章字数:92,阅读全文大约需要1分钟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

public class MyClassLoader extends ClassLoader {
//指定路径
private String path ;


public MyClassLoader(String classPath){
path=classPath;
}

/**
* 重写findClass方法
* @param name 是我们这个类的全路径
* @return
* @throws ClassNotFoundException
*/
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
Class log = null;
// 获取该class文件字节码数组
byte[] classData = getData();

if (classData != null) {
// 将class的字节码数组转换成Class类的实例
log = defineClass(name, classData, 0, classData.length);
}
return log;
}

/**
* 将class文件转化为字节码数组
* @return
*/
private byte[] getData() {

File file = new File(path);
if (file.exists()){
FileInputStream in = null;
ByteArrayOutputStream out = null;
try {
in = new FileInputStream(file);
out = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];
int size = 0;
while ((size = in.read(buffer)) != -1) {
out.write(buffer, 0, size);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {

e.printStackTrace();
}
}
return out.toByteArray();
}else{
return null;
}
}
}