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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
package cl;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class CustomClassLoader extends ClassLoader
{
public CustomClassLoader(){
super(CustomClassLoader.class.getClassLoader());
}
public Class loadClass( String name, boolean resolve )
throws ClassNotFoundException {
// Our goal is to get a Class object
Class clazz = null;
// First, see if we've already dealt with this one
clazz = findLoadedClass(name);
String fileStub = name.replace( '.', '/' );
String classFilename = "target/classes/" + fileStub+".class";
try {
// read the bytes
byte raw[] = getBytes( classFilename );
// try to turn them into a class
clazz = defineClass( name, raw, 0, raw.length );
} catch( IOException ex ) {
// This is not a failure! If we reach here, it might
// mean that we are dealing with a class in a library,
// such as java.lang.Object
}
// Maybe the class is in a library -- try loading
// the normal way
if (clazz==null) {
clazz = findSystemClass( name );
}
// Resolve the class, if any, but only if the "resolve"
// flag is set to true
if (resolve && clazz != null) {
resolveClass( clazz );
}
// If we still don't have a class, it's an error
if (clazz == null) {
throw new ClassNotFoundException( name );
}
return clazz;
}
// Given a filename, read the entirety of that file from disk
// and return it as a byte array.
private byte[] getBytes( String filename ) throws IOException {
// Find out the length of the file
File file = new File( filename );
long len = file.length();
// Create an array that's just the right size for the file's
// contents
byte raw[] = new byte[(int)len];
// Open the file
FileInputStream fin = new FileInputStream( file );
// Read all of it into the array; if we don't get all,
// then it's an error.
int r = fin.read( raw );
if (r != len) {
throw new IOException( "Can't read all, "+r+" != "+len );
}
// Don't forget to close the file!
fin.close();
// And finally return the file contents as an array
return raw;
}
}
|