I have a groovy script and i want to execute it in java. Could someone provide me with further documentation / examples on how this is possible?
With the GroovyClassLoader we can load Groovy scripts and run them in Java code. First we must create a new GroovyClassLoader and then parse a Groovy script. The script can be in a file, string or inputstream. Once the script is parsed we have a Class and we can make a new instance of this class.
Groovy scripts can use any Java classes. They can be compiled to Java bytecode (in . class files) that can be invoked from normal Java classes. The Groovy compiler, groovyc, compiles both Groovy scripts and Java source files, however some Java syntax (such as nested classes) is not supported yet.
Basic Java+Groovy Integration:
// call groovy expressions from Java code Binding binding = new Binding(); binding.setVariable("foo", new Integer(2)); GroovyShell shell = new GroovyShell(binding); Object value = shell.evaluate(groovyScript);
See this article for more ways to call Groovy from Java
PS: You need to include groovy-all-m.n.m.jar
e.g. groovy-all-2.1.6.jar
in your Java program, for example:
<dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>2.4.8</version> </dependency>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With