forked from Jossc/JavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoadClass.java
More file actions
57 lines (46 loc) · 1.54 KB
/
LoadClass.java
File metadata and controls
57 lines (46 loc) · 1.54 KB
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
package com.match;
import java.io.*;
/**
* @ClassName: LoadClass
* @Description TODO
* @Date 2019/1/23 17:04
* @Created by chenzhuo
**/
public class LoadClass extends ClassLoader {
public static String rootDir = "/Users/mac/Desktop/JavaCode/src/main/java/";
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return super.loadClass(name);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] bytes = getClassData(name);
if (null == bytes) {
throw new ClassNotFoundException();
} else {
return defineClass(name, bytes, 0, bytes.length);
}
}
private byte[] getClassData(String className) {
String path = classNameToPath(className);
try {
InputStream ins = new FileInputStream(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
int bytesNumRead = 0;
// 读取类文件的字节码
while ((bytesNumRead = ins.read(buffer)) != -1) {
baos.write(buffer, 0, bytesNumRead);
}
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String classNameToPath(String className) {
return rootDir + File.separatorChar + className.replace('.', File.separatorChar)
+ ".class";
}
}