1 import java.util.Hashtable;
4 public class TestLoader extends ClassLoader {
8 TestController controller_;
13 class ClassfileEntry extends Entry {
14 public String filename_;
15 public ClassfileEntry(String filename) { filename_ = filename; }
18 class DelegationEntry extends Entry {
19 public ClassLoader loader_;
20 public DelegationEntry(ClassLoader loader) { loader_ = loader; }
23 class SuperDelegationEntry extends Entry {
26 public TestLoader(ClassLoader parent, String name, TestController controller) {
29 controller_ = controller;
30 registry_ = new Hashtable();
33 public void addClassfile(String classname, String filename) {
34 registry_.put(classname, new ClassfileEntry(filename));
37 public void addDelegation(String classname, ClassLoader loader) {
38 registry_.put(classname, new DelegationEntry(loader));
41 public void addParentDelegation(String classname) {
42 registry_.put(classname, new DelegationEntry(getParent()));
45 public void addSuperDelegation(String classname) {
46 registry_.put(classname, new SuperDelegationEntry());
49 public String toString() {
50 return "TestLoader<" + name_ + ">";
53 public Class loadClass(String classname) throws ClassNotFoundException {
54 controller_.reportRequest(this, classname);
56 Entry entry = (Entry) registry_.get(classname);
59 controller_.reportUnexpectedClassRequested(this, classname);
60 throw new ClassNotFoundException(this + " does not know how to load class " + classname);
63 if (entry instanceof ClassfileEntry) {
64 Class cls = findLoadedClass(classname);
67 controller_.reportFoundLoaded(this, cls);
71 String filename = ((ClassfileEntry)entry).filename_;
74 byte[] bytes = slurpFile(filename);
76 cls = defineClass(classname, bytes, 0, bytes.length);
78 controller_.reportDefinition(this, cls);
83 throw new ClassNotFoundException(e.toString());
86 else if (entry instanceof DelegationEntry) {
87 ClassLoader delegate = ((DelegationEntry)entry).loader_;
89 controller_.reportDelegation(this, delegate, classname);
91 Class cls = delegate.loadClass(classname);
93 controller_.reportLoaded(this, cls);
98 throw new ClassNotFoundException("unknown TestLoader entry: " + entry);
101 byte[] slurpFile(String filename) throws IOException {
102 File file = new File(filename);
103 InputStream is = new FileInputStream(file);
104 long len = file.length();
105 if (len > Integer.MAX_VALUE)
106 throw new IOException("file " + file.getName() + " is too large");
107 byte[] bytes = new byte[(int) len];
111 while ((ofs < len) && (read = is.read(bytes, ofs, bytes.length - ofs)) >= 0)
115 throw new IOException("error reading file " + file.getName());