1 19 20 package asm2; 21 22 import java.io.PrintWriter ; 23 import java.net.URL ; 24 25 import org.objectweb.asm.ClassAdapter; 26 import org.objectweb.asm.ClassReader; 27 import org.objectweb.asm.ClassVisitor; 28 import org.objectweb.asm.ClassWriter; 29 import org.objectweb.asm.Constants; 30 import org.objectweb.asm.Type; 31 import org.objectweb.asm.attrs.Annotation; 32 import org.objectweb.asm.attrs.Attributes; 33 import org.objectweb.asm.attrs.RuntimeVisibleAnnotations; 34 import org.objectweb.asm.util.TraceClassVisitor; 35 36 37 public class MarkerClassLoader 38 extends ClassLoader { 39 40 private Class c; 41 42 public MarkerClassLoader( Class c) { 43 this.c = c; 44 } 45 46 public Class loadClass( String name) 47 throws ClassNotFoundException { 48 String resourceName = 49 "/"+name.replace( '.', '/')+".class"; 50 URL url = c.getResource( resourceName); 51 if( name.startsWith( "java") || 52 name.equals(Marker.class.getName()) || 53 url==null) { 54 return c.getClassLoader().loadClass( name); 55 } 56 57 ClassWriter cw = new ClassWriter(false); 58 try { 59 ClassReader cr = 60 new ClassReader(url.openStream()); 61 cr.accept(new MarkerClassVisitor(cw), 62 Attributes.getDefaultAttributes(), false); 63 64 byte[] b = cw.toByteArray(); 65 return defineClass( name, b, 0, b.length); 66 67 } catch( Exception ex) { 68 throw new ClassNotFoundException ( 69 "Unable to load class "+name); 70 71 } 72 } 73 74 75 public static class MarkerClassVisitor extends ClassAdapter { 76 77 public MarkerClassVisitor(ClassVisitor cv) { 78 super(cv); 79 } 80 81 public void visit( int version, int access, 82 String name, String superName, 83 String [] interfaces, String sourceFile) { 84 super.visit( Constants.V1_5, access, name, 85 superName, interfaces, sourceFile); 86 } 87 88 public void visitEnd() { 89 String t = Type.getDescriptor(Marker.class); 90 Annotation ann = new Annotation(t); 91 ann.add("value", "Class"); 92 93 RuntimeVisibleAnnotations attr = 94 new RuntimeVisibleAnnotations(); 95 attr.annotations.add(ann); 96 cv.visitAttribute(attr); 97 98 super.visitEnd(); 99 } 100 101 } 102 103 } 104 105 | Popular Tags |