Created
January 13, 2012 15:20
-
-
Save nickman/1606935 to your computer and use it in GitHub Desktop.
Example of Getting ByteCode From A Compiled Groovy Class
This file contains 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.* | |
// Compile a closure producing class | |
cu = new CompilationUnit(); | |
cu.addSource("ClosureFactory.groovy", "public class ClosureFactory { public Closure getClosure() { return {message -> println message} }; }"); | |
cu.compile(); | |
// Get the closure, the closure class bytes and invoke the closure. | |
clazz = Class.forName("ClosureFactory"); | |
clozure = clazz.newInstance().getClosure(); | |
clozureClass = clozure.getClass(); | |
bytes = clozureClass.getProtectionDomain().getCodeSource().getLocation().getBytes(); | |
println "Class [Name:${clozureClass.getName()}] Bytes:${bytes.length} Interfaces: ${clozureClass.getInterfaces()}"; | |
clozure("Hello Venus"); | |
// Create an "on the fly" closure | |
foo = {message -> println message}; | |
// Get the closure, the closure class bytes and invoke the closure. | |
clozureClass = foo.getClass(); | |
try { | |
bytes = clozureClass.getProtectionDomain().getCodeSource().getLocation().getBytes(); | |
} catch (e) { | |
println "Exception:${e.getMessage()}"; | |
bytes = []; | |
} | |
println "Class [Name:${clozureClass.getName()}] Bytes:${bytes} Interfaces: ${clozureClass.getInterfaces()}"; | |
foo("Hello Jupiter"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An easier way to get the bytes for the classes: