Created
January 13, 2012 20:58
-
-
Save nickman/1608660 to your computer and use it in GitHub Desktop.
On Demand ClassFileTransformer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.codehaus.groovy.control.* | |
| import org.codehaus.groovy.ast.ClassHelper; | |
| import org.helios.gmx.classloading.*; | |
| // Acquire the instrumentation instance | |
| def instrumentation = ByteCodeRepository.getInstance().agentInstrumentation.getInstrumentation(); | |
| // Define a closre | |
| foo = {message -> println message}; | |
| // Define a simple class file transformer | |
| class ByteCodeNet implements java.lang.instrument.ClassFileTransformer { | |
| def clazzName; | |
| def bytecode; | |
| public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, java.security.ProtectionDomain protectionDomain, byte[] classfileBuffer) { | |
| if(clazzName.equals(className)) { | |
| bytecode = classfileBuffer; | |
| } | |
| return classfileBuffer; | |
| } | |
| } | |
| // Instantiate class file transformer | |
| cft = new ByteCodeNet(clazzName: foo.getClass().getName()); | |
| // Holder for our bytecode | |
| def bytecode = null; | |
| try { | |
| // Register the class file transformer with the instrumentation | |
| instrumentation.addTransformer(cft, true); | |
| // Direct the instrumentation to retransform the closure class | |
| instrumentation.retransformClasses(foo.getClass()); | |
| // Grab the byte code from the class file transformer | |
| bytecode = cft.bytecode; | |
| } finally { | |
| // Unregister the class file transformer | |
| instrumentation.removeTransformer(cft); | |
| } | |
| // Voila | |
| println "Class:${foo.getClass().getName()} Bytes:${bytecode.length}"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment