Skip to content

Instantly share code, notes, and snippets.

@nickman
Created January 13, 2012 15:20
Show Gist options
  • Save nickman/1606935 to your computer and use it in GitHub Desktop.
Save nickman/1606935 to your computer and use it in GitHub Desktop.
Example of Getting ByteCode From A Compiled Groovy Class
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");
@renatoathaydes
Copy link

An easier way to get the bytes for the classes:

...
def className = ...

compilationUnit.compile()

def groovyClass = compilationUnit.classes.find { GroovyClass gc ->
    gc.name == className
} as GroovyClass

assert groovyClass, "CompilationUnit did not compile a class with name $className"

byte[] classBytes = groovyClass.bytes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment