Hello I am looking to run a groovy script inside Java code but I didn't find many tutorial about that.
I have a String that contain a groovy script :
private String processingCode = "def hello_world() { println \"Hello, world!\" }";
I have also downloaded the Groovy SDK.
Which groovy jar should I include in java project ? And how to execute the script in Java ?
With joint compilation, the Groovy compiler will: parse the source files. depending on the implementation, create stubs that are compatible with the Java compiler. invoke the Java compiler to compile the stubs along with Java sources – this way Java classes can find Groovy dependencies.
The best things about Groovy are that since it extends JDK, it accepts Java code. Groovy can be used as both programming and scripting Language.
What you need is a groovy-all
dependency and GroovyShell
.
Main class will be:
package lol;
import groovy.lang.GroovyShell;
public class Lol {
public static void main(String[] args) {
String processingCode = "def hello_world() { println 'Hello, world!' }; hello_world();";
GroovyShell shell = new GroovyShell();
shell.evaluate(processingCode);
}
}
Here is a demo.
Use gradle run
to run it.
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