1 16 17 package org.springframework.instrument.classloading; 18 19 import java.lang.instrument.ClassFileTransformer ; 20 import java.lang.reflect.Method ; 21 22 import org.apache.commons.logging.Log; 23 import org.apache.commons.logging.LogFactory; 24 25 import org.springframework.util.Assert; 26 import org.springframework.util.ClassUtils; 27 import org.springframework.util.ReflectionUtils; 28 29 64 public class ReflectiveLoadTimeWeaver implements LoadTimeWeaver { 65 66 private static final String ADD_TRANSFORMER_METHOD_NAME = "addTransformer"; 67 68 private static final String GET_THROWAWAY_CLASS_LOADER_METHOD_NAME = "getThrowawayClassLoader"; 69 70 private static final Log logger = LogFactory.getLog(ReflectiveLoadTimeWeaver.class); 71 72 73 private final ClassLoader classLoader; 74 75 private final Method addTransformerMethod; 76 77 private final Method getThrowawayClassLoaderMethod; 78 79 80 84 public ReflectiveLoadTimeWeaver() { 85 this(ClassUtils.getDefaultClassLoader()); 86 } 87 88 97 public ReflectiveLoadTimeWeaver(ClassLoader classLoader) { 98 Assert.notNull(classLoader, "ClassLoader must not be null"); 99 this.classLoader = classLoader; 100 this.addTransformerMethod = ClassUtils.getMethodIfAvailable( 101 this.classLoader.getClass(), ADD_TRANSFORMER_METHOD_NAME, 102 new Class [] {ClassFileTransformer .class}); 103 if (this.addTransformerMethod == null) { 104 throw new IllegalStateException ( 105 "ClassLoader [" + classLoader.getClass().getName() + "] does NOT provide an " + 106 "'addTransformer(ClassFileTransformer)' method."); 107 } 108 this.getThrowawayClassLoaderMethod = ClassUtils.getMethodIfAvailable( 109 this.classLoader.getClass(), GET_THROWAWAY_CLASS_LOADER_METHOD_NAME, 110 new Class [0]); 111 if (this.getThrowawayClassLoaderMethod == null) { 113 if (logger.isInfoEnabled()) { 114 logger.info("The ClassLoader [" + classLoader.getClass().getName() + "] does NOT provide a " + 115 "'getThrowawayClassLoader()' method; SimpleThrowawayClassLoader will be used instead."); 116 } 117 } 118 } 119 120 121 public void addTransformer(ClassFileTransformer transformer) { 122 Assert.notNull(transformer, "Transformer must not be null"); 123 ReflectionUtils.invokeMethod(this.addTransformerMethod, this.classLoader, new Object [] {transformer}); 124 } 125 126 public ClassLoader getInstrumentableClassLoader() { 127 return this.classLoader; 128 } 129 130 public ClassLoader getThrowawayClassLoader() { 131 if (this.getThrowawayClassLoaderMethod != null) { 132 return (ClassLoader ) ReflectionUtils.invokeMethod(this.getThrowawayClassLoaderMethod, this.classLoader, 133 new Object [0]); 134 } 135 else { 136 return new SimpleThrowawayClassLoader(this.classLoader); 137 } 138 } 139 140 } 141 | Popular Tags |