java-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
package anno;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class NetworkClassLoader extends ClassLoader {
private String path;

NetworkClassLoader(String file) {
path = file;
}

public Class findClass(String name) throws ClassNotFoundException {

byte[] b = new byte[0];
try {
b = loadClassData(name);
} catch (IOException e) {
e.printStackTrace();
}
return defineClass(name, b, 0, b.length);
}

private byte[] loadClassData(String name) throws IOException {
String classExtension = ".class";
File file = new File(path, name.replace('.', '/') + classExtension);
FileInputStream input = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len = -1;
while ((len = input.read()) != -1) {
out.write(len);
}
return out.toByteArray();
}

public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
NetworkClassLoader loader = new NetworkClassLoader("/Users/rick.xu/Downloads/groovy/src/main/java/");
Class cls = loader.findClass("anno.Person");
Object obj = cls.newInstance();
System.out.println(obj);
ClassLoader clsLoader = cls.getClassLoader();
while(clsLoader != null) {
System.out.println(clsLoader);
clsLoader = clsLoader.getParent();
}
System.out.println("阴道类加载器:" + clsLoader);
}
}

// output
anno.Person@4e25154f
anno.NetworkClassLoader@6d06d69c
sun.misc.Launcher$AppClassLoader@659e0bfd
sun.misc.Launcher$ExtClassLoader@70dea4e
引导类加载器:null

Author: Rick
Link: https://rcrick.github.io/2020/05/17/java-classLoader/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付寶