-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomClassLoader.java
More file actions
53 lines (44 loc) · 1.65 KB
/
CustomClassLoader.java
File metadata and controls
53 lines (44 loc) · 1.65 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
package ru.ispras.j8.manual;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class CustomClassLoader extends ClassLoader {
private final String PKG_PREFIX = "ru.ispras";
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
Class<?> c = findLoadedClass(name);
if (c != null)
return c;
if (name.startsWith(PKG_PREFIX)) {
c = findClass(name);
if (c != null) {
System.out.println("CCL: Loading " + name);
return c;
}
}
System.out.println("CCL: Delegating " + name);
return super.loadClass(name);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
String classFile = name.replace('.', File.separatorChar) + ".class";
System.out.println("CCL: Finding " + classFile);
try (InputStream inputStream = getResourceAsStream(classFile)) {
if (inputStream == null)
throw new ClassNotFoundException();
byte[] bytecode = readAllBytes(inputStream);
return defineClass(name, bytecode, 0, bytecode.length);
} catch (IOException e) {
throw new ClassNotFoundException();
}
}
private byte[] readAllBytes(InputStream inputStream) throws IOException {
int nextValue;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
while ((nextValue = inputStream.read()) != -1) {
byteStream.write(nextValue);
}
return byteStream.toByteArray();
}
}