Skip to content

Commit 9707414

Browse files
feat:完成自定义类加载器的自定义加载逻辑 (#3)
merge
1 parent 44a81af commit 9707414

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,74 @@
11
package club.shengsheng;
22

33

4+
import java.io.ByteArrayOutputStream;
5+
import java.io.File;
6+
import java.io.FileInputStream;
7+
import java.io.IOException;
8+
49
/**
510
* @author gongxuanzhangmelt@gmail.com
611
**/
712
public class MyClassLoader extends ClassLoader {
813

14+
/**
15+
* 重写findClass方法,让其查找我们指定路径下的class文件,并完成定义加载
16+
*
17+
* @param name
18+
* @return
19+
* @throws ClassNotFoundException
20+
*/
21+
@Override
22+
protected Class<?> findClass(String name) throws ClassNotFoundException {
23+
// 1、读取项目根目录中的加密.class文件,获取class文件的字节数组
24+
String projectDir = System.getProperty("user.dir"); // 获取项目根目录
25+
String filePath = projectDir + File.separator + "加密.class";
26+
byte[] classBytes = readClassFile(filePath);
27+
28+
if (classBytes == null) {
29+
throw new ClassNotFoundException("无法加载类:" + name);
30+
}
31+
32+
// 2、解密字节数组,并返回解密后的字节数组。解密规则:每个字节减1
33+
classBytes = decryptClassBytes(classBytes);
34+
35+
return defineClass(name, classBytes, 0, classBytes.length);
36+
}
37+
38+
private byte[] decryptClassBytes(byte[] classBytes) {
39+
for (int i = 0; i < classBytes.length; i++) {
40+
classBytes[i] = (byte) (classBytes[i] - 1);
41+
}
42+
return classBytes;
43+
}
44+
45+
/**
46+
* 读取class文件到字节数组
47+
*
48+
* @param filePath class文件路径
49+
* @return 字节数组 或 null
50+
*/
51+
private byte[] readClassFile(String filePath) {
52+
File file = new File(filePath);
53+
if (!file.exists()) {
54+
System.err.println("文件不存在: " + filePath);
55+
return null;
56+
}
57+
58+
try (FileInputStream fis = new FileInputStream(file);
59+
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
60+
61+
byte[] buffer = new byte[1024];
62+
int bytesRead;
63+
while ((bytesRead = fis.read(buffer)) != -1) {
64+
baos.write(buffer, 0, bytesRead);
65+
}
66+
return baos.toByteArray();
67+
68+
} catch (IOException e) {
69+
e.printStackTrace();
70+
return null;
71+
}
72+
}
73+
974
}

0 commit comments

Comments
 (0)