Skip to content

Commit e3c4eed

Browse files
committed
update > jvm test code
1 parent f30cb00 commit e3c4eed

3 files changed

Lines changed: 23 additions & 26 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
package classloader;
2-
31
/**
42
* Created by 李恒名 on 2017/6/8.
53
*/
64
public class Test {
5+
static {
6+
System.out.println("Test Initialize");
7+
}
78

8-
public void say (){
9+
public void say() {
910
System.out.println("Hello");
1011
}
1112
}

jvm/src/main/java/classloader/CustomClassLoader.java

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,21 @@
11
package classloader;
22

3-
import java.io.BufferedInputStream;
43
import java.io.ByteArrayOutputStream;
54
import java.io.FileInputStream;
65
import java.io.IOException;
6+
import java.lang.reflect.Method;
77

88
/**
99
* Created by 李恒名 on 2017/6/8.
1010
*/
1111
public class CustomClassLoader extends ClassLoader {
1212
private final String classesDir;
1313

14+
@Override
15+
public Class<?> loadClass(String name) throws ClassNotFoundException {
16+
return super.loadClass(name,true);
17+
}
18+
1419
public CustomClassLoader(String classesDir) {
1520
this.classesDir = classesDir;
1621
}
@@ -24,11 +29,11 @@ protected Class<?> findClass(String name) throws ClassNotFoundException {
2429
fileName = fileName + ".class";
2530

2631
try {
27-
try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(classesDir + fileName))) {
32+
try (FileInputStream in = new FileInputStream(classesDir + fileName)) {
2833
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
2934
byte[] buffer = new byte[1024];
3035
int len = 0;
31-
while ((len = bin.read(buffer)) != -1) {
36+
while ((len = in.read(buffer)) != -1) {
3237
out.write(buffer,0,len);
3338
}
3439
byte[] data = out.toByteArray();
@@ -41,4 +46,15 @@ protected Class<?> findClass(String name) throws ClassNotFoundException {
4146
}
4247
return super.findClass(name);
4348
}
49+
50+
public static void main(String[] args) throws ReflectiveOperationException{
51+
//1. 将Test.java 编译为Test.class 后复制到 E:\classes 下,当然也可以选择其他目录作为类加载器的classpath。
52+
//2. 加载
53+
ClassLoader classLoader = new CustomClassLoader("E:\\classes\\");
54+
Class<?> clazz = classLoader.loadClass("Test");//如果你的Test在一个包内,需要加上包名,如x.y.z.Test
55+
//3. 通过反射调用say()方法
56+
Object instance = clazz.newInstance();
57+
Method method = clazz.getMethod("say", null);
58+
method.invoke(instance);//Hello
59+
}
4460
}

jvm/src/main/java/classloader/Tester.java

Lines changed: 0 additions & 20 deletions
This file was deleted.

0 commit comments

Comments
 (0)