Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run groovy script in java?

Tags:

java

groovy

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?

like image 581
user648244 Avatar asked Jul 22 '13 14:07

user648244


People also ask

How do I run a Groovy file in Java?

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.

Can I run Groovy with Java?

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.


1 Answers

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> 
like image 185
anubhava Avatar answered Sep 30 '22 09:09

anubhava