Skip to content

Commit ec90ae1

Browse files
committed
add > custom-class-loader
1 parent d38c64f commit ec90ae1

3 files changed

Lines changed: 75 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package classloader;
2+
3+
import java.io.BufferedInputStream;
4+
import java.io.ByteArrayOutputStream;
5+
import java.io.FileInputStream;
6+
import java.io.IOException;
7+
8+
/**
9+
* Created by 李恒名 on 2017/6/8.
10+
*/
11+
public class CustomClassLoader extends ClassLoader {
12+
private final String classesDir;
13+
14+
public CustomClassLoader(String classesDir) {
15+
this.classesDir = classesDir;
16+
}
17+
18+
@Override
19+
protected Class<?> findClass(String name) throws ClassNotFoundException {
20+
String fileName = name;
21+
if (fileName.indexOf('.') > 0) {
22+
fileName.replaceAll(".", "\\");
23+
}
24+
fileName = fileName + ".class";
25+
26+
try {
27+
try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(classesDir + fileName))) {
28+
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
29+
byte[] buffer = new byte[1024];
30+
int len = 0;
31+
while ((len = bin.read(buffer)) != -1) {
32+
out.write(buffer,0,len);
33+
}
34+
byte[] data = out.toByteArray();
35+
return defineClass(name, data, 0, data.length);
36+
}
37+
}
38+
39+
} catch (IOException e) {
40+
e.printStackTrace();
41+
}
42+
return super.findClass(name);
43+
}
44+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package classloader;
2+
3+
/**
4+
* Created by 李恒名 on 2017/6/8.
5+
*/
6+
public class Test {
7+
8+
public void say (){
9+
System.out.println("Hello");
10+
}
11+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package classloader;
2+
3+
import java.lang.reflect.Method;
4+
5+
/**
6+
* Created by 李恒名 on 2017/6/8.
7+
*/
8+
public class Tester {
9+
10+
public static void main(String[] args) throws Exception{
11+
//1. 将Test.java 编译为Test.class 后复制到 E:\classes 下,当然也可以选择其他目录。
12+
//2. 加载
13+
ClassLoader classLoader = new CustomClassLoader("E:\\classes\\");
14+
Class<?> clazz = classLoader.loadClass("Test");
15+
//3. 通过反射调用say()方法
16+
Object instance = clazz.newInstance();
17+
Method method = clazz.getMethod("say", null);
18+
method.invoke(instance);//Hello
19+
}
20+
}

0 commit comments

Comments
 (0)