Suppose I downloaded and executed a Groovy script in Java. Now I have an instance of the object of the groovy.lang.Script class. I can call functions from it using invokeMethod. What to do if a class was declared in the script and I know its name, but I need to create an instance of such a class in Java?
GroovyShell shell = new GroovyShell(); Script script = shell.parse(new File("/path/to/script.groovy")); script.run(); script.invokeMethod("foo", new Object[] { "bar" }); The code above loads the script from a file, executes it, and then pulls the function foo declared in it with the parameter bar. And what if I want to pull not only functions, but also classes?
UPD:
I was able to make code that would load the class from the script:
private static Class loadClassFromScript(Script script, String className) throws ClassNotFoundException { final Package package_ = script.getClass().getPackage(); final String classNamePrefix = (package_ != null) ? package_.getName() + "." : ""; return Class.forName(classNamePrefix + className, true, script.getClass().getClassLoader()); } It works fine except when the script does not contain executable constructs, but only a class declaration. What to do in this case?