Skip to content

Instantly share code, notes, and snippets.

@ppazos
Last active February 7, 2024 20:03
Show Gist options
  • Save ppazos/8033899 to your computer and use it in GitHub Desktop.
Save ppazos/8033899 to your computer and use it in GitHub Desktop.
Groovy load a class from String
GroovyClassLoader gcl = new GroovyClassLoader ();
try {
glc.parseClass (inputString);
// do stuff
} catch (CompilationFailedExcpetion cfe) {
// can't do stuff
}
/* https://stackoverflow.com/questions/9004303/load-script-from-groovy-script
http://groovy-lang.org/integrating.html#integ-groovyshell
http://www.javased.com/?api=groovy.lang.GroovyShell
https://www.mscharhag.com/groovy/groovy-shell
= Script
File1.groovy
def method() {
println "test"
}
Loader.groovy
new GroovyShell().parse( new File( 'file1.groovy' ) ).with {
method()
}
= Script 2
GroovyShell shell = new GroovyShell()
def script = shell.parse(new File('/path/file1.groovy'))
script.method()
= Class
File2.groovy
class File2 {
def method() {
println "test"
}
}
Loader2.groovy
def script = new GroovyScriptEngine( '.' ).with {
loadScriptByName( 'File2.groovy' )
}
this.metaClass.mixin script
method()
= Class 2
this.class.classLoader.parseClass("src/File1.groovy")
File1.method()
File1.newInstance().anotherMethod()
= Class 3
def myclass = this.class.classLoader.parseClass("src/File1.groovy")
def myobject = myclass.newInstance()
myobject.method()
= Run with debug
CompilerConfiguration cc = CompilerConfiguration.DEFAULT
cc.setDebug(true) def shell = new GroovyShell(Thread.currentThread().getContextClassLoader(), binding, cc)
scriptUrl = Thread.currentThread().getContextClassLoader().getResource(it);
GroovyCodeSource gcs = new GroovyCodeSource(scriptUrl);
Script s = shell.parse(gcs); s.run();
= Script evaluate
def binding = new Binding();
binding.lineList = [list1];
binding.count = 5;
def shell = new GroovyShell(binding);
def result = shell.evaluate(new File("src/Rules/checkLimit.groovy"));
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment