1 33 34 package edu.rice.cs.util.classloader; 35 36 import java.util.Arrays ; 37 import java.net.URL ; 38 import java.io.IOException ; 39 import java.io.InputStream ; 40 41 import edu.rice.cs.plt.io.IOUtil; 42 import edu.rice.cs.util.FileOps; 43 44 65 public class StickyClassLoader extends ClassLoader { 66 private final ClassLoader _newLoader; 67 private final String [] _classesToLoadWithOld; 68 69 74 public StickyClassLoader(final ClassLoader newLoader, final ClassLoader oldLoader) { 75 this(newLoader, oldLoader, new String [0]); 76 } 77 78 91 public StickyClassLoader(final ClassLoader newLoader, final ClassLoader oldLoader, 92 final String [] classesToLoadWithOld) { 93 super(oldLoader); 94 _newLoader = newLoader; _classesToLoadWithOld = new String [classesToLoadWithOld.length]; 96 System.arraycopy(classesToLoadWithOld, 0, _classesToLoadWithOld, 0, classesToLoadWithOld.length); 97 Arrays.sort(_classesToLoadWithOld); 98 } 99 100 104 public URL getResource(String name) { 105 URL resource = _newLoader.getResource(name); 106 if (resource == null) resource = getParent().getResource(name); 107 108 return resource; 110 } 111 112 127 protected Class <?> loadClass(String name, boolean resolve) throws ClassNotFoundException { 128 Class <?> clazz; 130 clazz = findLoadedClass(name); 131 if (clazz != null) return clazz; 132 133 if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("sun.") || 134 name.startsWith("com.sun.") || name.startsWith("org.omg.") || name.startsWith("sunw.") || 135 name.startsWith("org.w3c.dom.") || name.startsWith("org.xml.sax.") || name.startsWith("net.jini.")) { 136 137 try { clazz = getSystemClassLoader().loadClass(name); } 138 catch (ClassNotFoundException e) { 139 clazz = _loadWithSecondary(name); 142 } 143 } 144 else if (Arrays.binarySearch(_classesToLoadWithOld, name) >= 0) { 145 clazz = getParent().loadClass(name); 147 } 148 else { 149 clazz = _loadWithSecondary(name); 151 } 155 156 if (resolve) resolveClass(clazz); 157 158 return clazz; 160 } 161 162 165 protected Class _loadWithSecondary(String name) throws ClassNotFoundException { 166 try { 172 String fileName = name.replace('.', '/') + ".class"; 173 174 URL resource = getResource(fileName); if (resource == null) { 176 throw new ClassNotFoundException ("Resource not found: " + fileName); 177 } 178 179 InputStream in = resource.openStream(); 180 try { 181 byte[] data = IOUtil.toByteArray(in); 182 return defineClass(name, data, 0, data.length); 183 } 184 finally { in.close(); } 185 } 186 catch (IOException ioe) { 187 throw new ClassNotFoundException (ioe.toString()); 188 } 189 } 190 } 191 | Popular Tags |