forked from 58code/Argo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyClassLoader1.java
More file actions
53 lines (44 loc) · 1.26 KB
/
MyClassLoader1.java
File metadata and controls
53 lines (44 loc) · 1.26 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
package learn;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
/**
* @author haojian
*
*/
public class MyClassLoader1 extends ClassLoader {
public MyClassLoader1(ClassLoader parent) {
super(parent);
}
public Class<?> findClass1(String name) throws Exception {
byte[] bytes = loadClassBytes(name);
Class theClass = defineClass(null, bytes, 0, bytes.length);
if (theClass == null)
throw new ClassFormatError();
return theClass;
}
private byte[] loadClassBytes(String classFile) throws Exception {
// String classFile = getClassFile();
FileInputStream fis = new FileInputStream(classFile);
FileChannel fileC = fis.getChannel();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
WritableByteChannel outC = Channels.newChannel(baos);
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
while (true) {
int i = fileC.read(buffer);
if (i == 0 || i == -1) {
break;
}
buffer.flip();
outC.write(buffer);
buffer.clear();
}
fis.close();
return baos.toByteArray();
}
}