实现自己的ClassLoader

自己实现一个简单ClassLoader.

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
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/***
* @ author Jay
*
*/
public class MyClassLoader extends ClassLoader
{

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException
{
byte[] classData = loadClassData(name);
if (classData == null)
{
throw new ClassNotFoundException();

}
else
{
return defineClass(name, classData, 0, classData.length);

}

}

private byte[] loadClassData(String name)
{
String fileName = "TestClassLoader.class";
try
{
InputStream ins = new FileInputStream(fileName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = 0;
while ((length = ins.read(buffer)) != -1)
{
baos.write(buffer, 0, length);

}
return baos.toByteArray();

}
catch (IOException e)
{
e.printStackTrace();

}
return null;

}

public static void main(String[] ar)
throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
ClassLoader loader = new MyClassLoader();
Class<?> cl = loader.loadClass("classLoader.TestClassLoader");
TestClassLoader t = (TestClassLoader) cl.newInstance();
t.main(null);
t.methodForTest();

}


}