forked from mockito/mockito
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReplicatingClassLoader.java
61 lines (54 loc) · 1.94 KB
/
ReplicatingClassLoader.java
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
60
61
/*
* Copyright (c) 2018 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import org.mockito.Mockito;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
public class ReplicatingClassLoader extends URLClassLoader {
public ReplicatingClassLoader(Path path) throws MalformedURLException {
super(new URL[]{path.toUri().toURL()}, null);
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
try {
return super.loadClass(name);
} catch (ClassNotFoundException e) {
InputStream in = Mockito.class.getClassLoader().getResourceAsStream(name.replace('.', '/') + ".class");
if (in == null) {
throw e;
} else {
try {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = (in.read(buffer))) != -1) {
out.write(buffer, 0, length);
}
byte[] b = out.toByteArray();
return defineClass(name, b, 0, b.length);
} finally {
in.close();
}
} catch (IOException e1) {
throw new RuntimeException(e1);
}
}
}
}
@Override
protected URL findResource(String moduleName, String name) {
return Mockito.class.getResource("/" + name);
}
@Override
public InputStream getResourceAsStream(String name) {
return Mockito.class.getResourceAsStream("/" + name);
}
}