1 16 package net.sf.cglib.transform; 17 18 import net.sf.cglib.core.CodeGenerationException; 19 import net.sf.cglib.core.ClassGenerator; 20 import net.sf.cglib.core.DebuggingClassWriter; 21 import org.objectweb.asm.ClassReader; 22 import org.objectweb.asm.ClassWriter; 23 import org.objectweb.asm.util.*; 24 import org.objectweb.asm.Attribute; 25 26 import java.io.IOException ; 27 28 abstract public class AbstractClassLoader extends ClassLoader { 29 private ClassFilter filter; 30 private ClassLoader classPath; 31 private static java.security.ProtectionDomain DOMAIN ; 32 33 static{ 34 35 DOMAIN = (java.security.ProtectionDomain ) 36 java.security.AccessController.doPrivileged( 37 new java.security.PrivilegedAction () { 38 public Object run() { 39 return AbstractClassLoader.class.getProtectionDomain(); 40 } 41 }); 42 } 43 44 protected AbstractClassLoader(ClassLoader parent, ClassLoader classPath, ClassFilter filter) { 45 super(parent); 46 this.filter = filter; 47 this.classPath = classPath; 48 } 49 50 public Class loadClass(String name) throws ClassNotFoundException { 51 52 Class loaded = findLoadedClass(name); 53 54 if( loaded != null ){ 55 if( loaded.getClassLoader() == this ){ 56 return loaded; 57 } } 59 60 if (!filter.accept(name)) { 61 return super.loadClass(name); 62 } 63 ClassReader r; 64 try { 65 66 java.io.InputStream is = classPath.getResourceAsStream( 67 name.replace('.','/') + ".class" 68 ); 69 70 if (is == null) { 71 72 throw new ClassNotFoundException (name); 73 74 } 75 try { 76 77 r = new ClassReader(is); 78 79 } finally { 80 81 is.close(); 82 83 } 84 } catch (IOException e) { 85 throw new ClassNotFoundException (name + ":" + e.getMessage()); 86 } 87 88 try { 89 ClassWriter w = new DebuggingClassWriter(true); 90 getGenerator(r).generateClass( w ); 91 byte[] b = w.toByteArray(); 92 Class c = super.defineClass(name, b, 0, b.length, DOMAIN); 93 postProcess(c); 94 return c; 95 } catch (RuntimeException e) { 96 throw e; 97 } catch (Error e) { 98 throw e; 99 } catch (Exception e) { 100 throw new CodeGenerationException(e); 101 } 102 } 103 104 protected ClassGenerator getGenerator(ClassReader r) { 105 return new ClassReaderGenerator(r, attributes(), skipDebug()); 106 } 107 108 protected boolean skipDebug() { 109 return false; 110 } 111 112 protected Attribute[] attributes() { 113 return null; 114 } 115 116 protected void postProcess(Class c) { 117 } 118 } 119 | Popular Tags |