Home
Categories
Dictionary
Download
Project Details
Changes Log
FAQ
License

Groovy tutorial



This tutorial explains how to load a Groovy script and use it from Java.

Overview

We will define a Script interface, and run a Groovy Script as a class which implements this interface from Java.

Define the Script interface

Our interface will be very simple. We will have the following definition for the interface.
      public interface Script {
        public int execute();
      }

Define the Groovy script wrapper and getting the Script proxy

We will extend the GroovyScriptWrapper in the Groovy language to define that our scripts implement our script interface. We will have the following simple class:
      public class GroovyScriptWrapperImpl extends GroovyScriptWrapper<Script> {
      }
With this definition, we have defined that our wrapper wrap scripts which implement the Script interface.

Then we will simply use the ScriptWrapper.getScriptProxy() method to get a proxy which will implement our interface:
      ScriptWrapper<Script> wrapper = new GroovyScriptWrapperImpl();
      Script script = wrapper.getScript();
Note that we also could do all of this with the more simple code:
      ScriptWrapper<Script> wrapper = new GroovyScriptWrapper<Script>(){
      };

Use the scripting runtime

We have the following Groovy script:
      public int execute() {
        return 10;
      }
We can now install the Script:
      File file = new File(<our script file>);
      Script script = wrapper.installScript(file);
And now we can run the method:
      int value = script.execute();
      // value is 10

See also


Categories: tutorials

Copyright 2019-2020 Herve Girod. All Rights Reserved. Documentation and source under the BSD licence