KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hansel > ProbeTableClassLoader


1 package org.hansel;
2
3 import java.io.ByteArrayOutputStream JavaDoc;
4 import java.io.InputStream JavaDoc;
5 import java.io.IOException JavaDoc;
6 import java.util.MissingResourceException JavaDoc;
7
8 public class ProbeTableClassLoader extends ClassLoader JavaDoc {
9     private Class JavaDoc probeTable;
10
11     public ProbeTableClassLoader(ClassLoader JavaDoc parent) {
12         super(parent);
13         probeTable = createClass(ProbeTable.class.getName());
14     }
15
16     public Class JavaDoc loadClass(String JavaDoc name) throws ClassNotFoundException JavaDoc {
17         if (ProbeTable.class.getName().equals(name)) {
18             return probeTable;
19         }
20             
21         return super.loadClass(name);
22     }
23
24     public Class JavaDoc getProbeTable() {
25         return probeTable;
26     }
27
28     private byte[] ressourceToByteArray(String JavaDoc ressourceName,
29                                         String JavaDoc classname) {
30         InputStream JavaDoc is = getClass().getClassLoader()
31                          .getResourceAsStream(ressourceName);
32
33         if (is == null) {
34             throw new MissingResourceException JavaDoc("Cannot find " +
35                                                classname + ".",
36                                                ProbeTable.class.getName(),
37                                                ressourceName);
38         }
39
40         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
41         byte[] data = new byte[1024];
42
43         try {
44             int count = is.read(data);
45             while (count != -1) {
46                 baos.write(data, 0, count);
47                 count = is.read(data);
48             }
49         } catch (IOException JavaDoc e) {
50             throw new MissingResourceException JavaDoc("Cannot read class"
51                                                + e.getMessage(),
52                                                classname,
53                                                ressourceName);
54         }
55
56         return baos.toByteArray();
57     }
58
59     private Class JavaDoc createClass(String JavaDoc classname) {
60         String JavaDoc ressourceName = classname.replace('.', '/') + ".class";
61         byte[] classdata = ressourceToByteArray(ressourceName, classname);
62
63         return defineClass(classname,
64                            classdata,
65                            0 , classdata.length);
66     }
67 }
68
Popular Tags