1 16 17 package org.springframework.instrument.classloading; 18 19 import java.lang.instrument.ClassFileTransformer ; 20 import java.lang.instrument.IllegalClassFormatException ; 21 import java.security.ProtectionDomain ; 22 import java.util.ArrayList ; 23 import java.util.List ; 24 25 37 public class WeavingTransformer { 38 39 private final ClassLoader classLoader; 40 41 private final List <ClassFileTransformer > transformers = new ArrayList <ClassFileTransformer >(); 42 43 44 47 public WeavingTransformer() { 48 this(null); 49 } 50 51 55 public WeavingTransformer(ClassLoader classLoader) { 56 this.classLoader = (classLoader != null ? classLoader :getDefaultClassLoader()); 57 } 58 59 60 64 public void addTransformer(ClassFileTransformer transformer) { 65 if (transformer == null) { 66 throw new IllegalArgumentException ("Transformer must not be null"); 67 } 68 this.transformers.add(transformer); 69 } 70 71 72 81 public byte[] transformIfNecessary(String className, byte[] bytes) { 82 String internalName = className.replace(".", "/"); 83 return transformIfNecessary(className, internalName, bytes, null); 84 } 85 86 98 public byte[] transformIfNecessary(String className, String internalName, byte[] bytes, ProtectionDomain pd) { 99 byte[] result = bytes; 100 for (ClassFileTransformer cft : this.transformers) { 101 try { 102 byte[] transformed = cft.transform(this.classLoader, internalName, null, pd, result); 103 if (transformed != null) { 104 result = transformed; 105 } 106 } 107 catch (IllegalClassFormatException ex) { 108 throw new IllegalStateException ("Class file transformation failed", ex); 109 } 110 } 111 return result; 112 } 113 114 115 119 protected ClassLoader getDefaultClassLoader() { 120 ClassLoader cl = Thread.currentThread().getContextClassLoader(); 121 if (cl == null) { 122 cl = getClass().getClassLoader(); 124 } 125 return cl; 126 } 127 128 } 129 | Popular Tags |