7

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 ?

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

4 Comments

There is no groovy-all in my groovy-sdk/lib directory, should I include the whole sdk ?
I guess all you need can be found under $GROOVY_HOME/lib.
My install has groovy-all.jar in $GROOVY_HOME/embedded
I've added the groovy-"version number".jar that is in my sdk and it worked. Thank you !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.