Home
Categories
Dictionary
Download
Project Details
Changes Log
FAQ
License

Groovy wrappers tutorial



This tutorial explains how to load a Groovy script and use it from Java. In that case, contrary to the First tutorial, we will explictly create a wrapper for our method.

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

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.

Define a Groovy method wrapper

Now we will define a wrapper for the execute() method. This method has an int return value, so we will extend the AbstractScriptMethodProxy class as follows:
      public class MethodWrapperImpl extends AbstractScriptMethodWrapper<Script, Integer> {

        public MethodWrapperImpl(ScriptWrapper<Script> wrapper) {
          super(wrapper);
        }

        protected Integer executeScriptImpl(Object[] arguments) {
          return script.execute();
        }
      }

Use the scripting runtime

First we create the ScriptWrapper:
      ScriptWrapper<Script> wrapper = new GroovyScriptWrapperImpl();
Then we create the wrapper around the execute() method[1]
You are not obliged to create the ScriptMethodWrapper after the script has been installed, you can do it as soon as you have created your ScriptWrapper
:
      ScriptMethodWrapper<Script, Integer> methodWrapper = new MethodWrapperImpl(wrapper);
We have the following Groovy script:
      public int execute() {
        return 10;
      }
We can now install the Script:
      File file = new File(<our script file>);
      wrapper.installScript(file);
And now we can run the method:
      int value = methodWrapper.executeMethod();
      // value is 10

Notes

  1. ^ You are not obliged to create the ScriptMethodWrapper after the script has been installed, you can do it as soon as you have created your ScriptWrapper


Categories: tutorials

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