Last active
August 29, 2015 13:56
-
-
Save jimwhite/9224553 to your computer and use it in GitHub Desktop.
A GroovyClassLoader that gathers up the bytecode that defines the classes it has compiled.
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.ast.ClassNode | |
import org.codehaus.groovy.control.CompilationUnit | |
import org.codehaus.groovy.control.SourceUnit | |
class MyGroovyClassLoader extends GroovyClassLoader { | |
MyGroovyClassLoader(ClassLoader parent) { super(parent) } | |
Map bytecodes = [:] | |
class MyClassCollector extends GroovyClassLoader.ClassCollector { | |
protected MyClassCollector(GroovyClassLoader.InnerLoader cl, CompilationUnit unit, SourceUnit su) { | |
super(cl, unit, su) | |
} | |
@Override | |
protected Class createClass(byte[] code, ClassNode classNode) { | |
bytecodes[classNode.name] = code | |
super.createClass(code, classNode) | |
} | |
} | |
@Override | |
protected GroovyClassLoader.ClassCollector createCollector(CompilationUnit unit, SourceUnit su) { | |
new MyClassCollector(new GroovyClassLoader.InnerLoader(this), unit, su) | |
} | |
} | |
def loader = new MyGroovyClassLoader(this.class.classLoader) | |
def scriptClassName = 'ScriptNameToLookFor' | |
// Compile via GroovyClassLoader: | |
// def script = loader.parseClass('println \'Hello\'', scriptClassName + '.groovy') | |
// Or go through GroovyShell: | |
def shell = new GroovyShell() | |
shell.loader = loader // Work around borked API/implementation | |
def script = shell.parse('println \'Hello\'', scriptClassName + '.groovy') | |
println loader.bytecodes.collectEntries { k, v -> [k, v.length] } | |
// ==> | |
// [ScriptNameToLookFor:6010] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment