-
Notifications
You must be signed in to change notification settings - Fork 841
Expand file tree
/
Copy pathXlassLoader.java
More file actions
75 lines (70 loc) · 2.61 KB
/
XlassLoader.java
File metadata and controls
75 lines (70 loc) · 2.61 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
/*
第一周作业:
2.(必做)自定义一个 Classloader,加载一个 lib.Hello.xlass 文件,执行 hello 方法,此文件内容是一个 lib.Hello.class 文件所有字节(x=255-x)处理后的文件。文件群里提供。
*/
public class XlassLoader extends ClassLoader {
public static void main(String[] args) throws Exception {
// 相关参数
final String packageName = "lib";
final String className = "Hello";
final String methodName = "hello";
// 创建类加载器
ClassLoader classLoader = new XlassLoader();
// 加载相应的类
Class<?> clazz = classLoader.loadClass(packageName + "." + className);
// 看看里面有些什么方法
for (Method m : clazz.getDeclaredMethods()) {
System.out.println(clazz.getSimpleName() + "." + m.getName());
}
// 创建对象
Object instance = clazz.getDeclaredConstructor().newInstance();
// 调用实例方法
Method method = clazz.getMethod(methodName);
method.invoke(instance);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
// 如果支持包名, 则需要进行路径转换
String resourcePath = name.replace(".", "/");
// 文件后缀
final String suffix = ".xlass";
// 获取输入流
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(resourcePath + suffix);
try {
// 读取数据
int length = inputStream.available();
byte[] byteArray = new byte[length];
inputStream.read(byteArray);
// 转换
byte[] classBytes = decode(byteArray);
// 通知底层定义这个类
return defineClass(name, classBytes, 0, classBytes.length);
} catch (IOException e) {
throw new ClassNotFoundException(name, e);
} finally {
close(inputStream);
}
}
// 解码
private static byte[] decode(byte[] byteArray) {
byte[] targetArray = new byte[byteArray.length];
for (int i = 0; i < byteArray.length; i++) {
targetArray[i] = (byte) (255 - byteArray[i]);
}
return targetArray;
}
// 关闭
private static void close(Closeable res) {
if (null != res) {
try {
res.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}