-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathNetworkClassLoader.java
More file actions
49 lines (43 loc) · 1.46 KB
/
Copy pathNetworkClassLoader.java
File metadata and controls
49 lines (43 loc) · 1.46 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
package classloader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
/**
* Load class from network
*/
public class NetworkClassLoader extends ClassLoader {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] classData = downloadClassData(name);
if (classData == null) {
super.findClass(name);
} else {
return defineClass(name, classData, 0, classData.length);
}
return null;
}
private byte[] downloadClassData(String name) {
String path = "http://localhost" + File.separatorChar + "java" + File.separatorChar + name.replace('.', File.separatorChar) + ".class";
System.out.printf("localPath: %s\n", path);
try {
URL url = new URL(path);
InputStream ins = url.openStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
int bytesNumRead = 0;
while ((bytesNumRead = ins.read(buffer)) != -1) {
baos.write(buffer, 0, bytesNumRead);
}
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getName() {
System.out.printf("Real NetworkClassLoader\n");
return "networkClassLoader";
}
}