Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running groovy script in Java code

Tags:

java

groovy

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 ?

like image 763
Steeven_b Avatar asked Jan 15 '16 14:01

Steeven_b


People also ask

Can you mix Java and Groovy?

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.

Does Groovy support Java?

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.


1 Answers

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.

like image 81
Opal Avatar answered Oct 12 '22 23:10

Opal