1 package org.hansel; 2 3 import java.io.ByteArrayOutputStream ; 4 import java.io.InputStream ; 5 import java.io.IOException ; 6 import java.util.MissingResourceException ; 7 8 public class ProbeTableClassLoader extends ClassLoader { 9 private Class probeTable; 10 11 public ProbeTableClassLoader(ClassLoader parent) { 12 super(parent); 13 probeTable = createClass(ProbeTable.class.getName()); 14 } 15 16 public Class loadClass(String name) throws ClassNotFoundException { 17 if (ProbeTable.class.getName().equals(name)) { 18 return probeTable; 19 } 20 21 return super.loadClass(name); 22 } 23 24 public Class getProbeTable() { 25 return probeTable; 26 } 27 28 private byte[] ressourceToByteArray(String ressourceName, 29 String classname) { 30 InputStream is = getClass().getClassLoader() 31 .getResourceAsStream(ressourceName); 32 33 if (is == null) { 34 throw new MissingResourceException ("Cannot find " + 35 classname + ".", 36 ProbeTable.class.getName(), 37 ressourceName); 38 } 39 40 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 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 e) { 50 throw new MissingResourceException ("Cannot read class" 51 + e.getMessage(), 52 classname, 53 ressourceName); 54 } 55 56 return baos.toByteArray(); 57 } 58 59 private Class createClass(String classname) { 60 String 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 |