-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMyClassLoader.java
More file actions
59 lines (50 loc) · 1.72 KB
/
Copy pathMyClassLoader.java
File metadata and controls
59 lines (50 loc) · 1.72 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
package clazz;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MyClassLoader extends ClassLoader{
// @Override
// public Class<?> loadClass(String name) throws ClassNotFoundException {
// return findClass(name);
// }
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
String classPath = MyClassLoader.class.getResource("/").getPath(); //得到classpath
String fileName = name.replace(".", "/") + ".class" ;
File classFile = new File(classPath , fileName);
if(!classFile.exists()){
throw new ClassNotFoundException(classFile.getPath() + " 不存在") ;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
ByteBuffer bf = ByteBuffer.allocate(1024) ;
FileInputStream fis = null ;
FileChannel fc = null ;
try {
fis = new FileInputStream(classFile) ;
fc = fis.getChannel() ;
while(fc.read(bf) > 0){
bf.flip() ;
bos.write(bf.array(),0 , bf.limit()) ;
bf.clear() ;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
fis.close() ;
fc.close() ;
} catch (IOException e) {
e.printStackTrace();
}
}
byte[] bytes = bos.toByteArray();
return defineClass(name,
bytes, 0, bytes.length);
}
}