I can successfully compile Groovy in Java at runtime and save it to the database and pull it out. I cannot compile a Groovy class if it has inner classes or inner enumeration. Has anyone successfully compiled Groovy code like this and included inner classes / enums and was able to get the script out of the class?
For example, I want to download the following “Test” script containing inner classes and run the script at runtime.
Compiler code:
public byte[] compileGroovyScript(final String className, final String script) { byte[] compiledScriptBytes = null; CompilationUnit compileUnit = new CompilationUnit(); compileUnit.addSource(className, script); compileUnit.compile(Phases.CLASS_GENERATION); for (Object compileClass : compileUnit.getClasses()) { GroovyClass groovyClass = (GroovyClass) compileClass; compiledScriptBytes = groovyClass.getBytes(); } return compiledScriptBytes; }
Code to pull script out:
public Class getGroovyScript(final String className, final byte[] script) { Class clazz = null; try (GroovyClassLoader classLoader = new GroovyClassLoader(this.getClass().getClassLoader())) { clazz = classLoader.defineClass(className, script); } catch (IOException e) { } catch (Exception e) { } return clazz; }
Code to run the script:
Class groovyClass = app.getGroovyScript(className, compiledScript); TestScript script = (TestScript) groovyClass.newInstance(); System.out.println(script.getMessage());
Groovy script:
import com.groovy.groovy.TestScript class Test implements TestScript { String getMessage() { [1..10].each(){ println it } return "Jello" } }
java groovy runtime-compilation
Colinmc
source share