Script
interface with one method only. This method had no arguments and a return value. In this tutorial, we will add more methods in our in Script
interface.
Script
interface, and run a Groovy Script as a class which implements this interface from Java.
Script
interface:public interface Script { public void doSomething(); public int compute(int value1, int value2); }
public class GroovyScriptWrapperImpl extends GroovyScriptWrapper<Script> { }
doSomething()
method with no return valuecompute(int value1, int value2)
method with two int argumentspublic class MethodWrapperImpl2 extends AbstractScriptMethodWrapper<Script, Integer> { public MethodWrapperImpl2(ScriptWrapper<Script> wrapper) { super(wrapper); } protected Integer executeScriptImpl(Object[] arguments) { Integer i1 = (Integer)arguments[0]; Integer i2 = (Integer)arguments[1]; return script.compute(i1, i2); } }
public class MethodWrapperImpl3 extends AbstractVoidScriptMethodWrapper<Script> { public MethodWrapperImpl3(ScriptWrapper<Script> wrapper) { super(wrapper); } protected void executeScriptImpl(Object[] arguments) { return script.doSomething(); } }
public int execute() { return 10; } public void doSomething() { System.out.println("I am here"); } public int compute(int i1, int i2) { return i1 + i2; }We create the ScriptWrapper exactly as in the first tutorial:
ScriptWrapper<Script> wrapper = new GroovyScriptWrapperImpl();Then we create the wrappers around the
compute(int value1, int value2)
and doSomething()
methods:ScriptMethodWrapper<Script, Integer> methodWrapper2 = new MethodWrapperImpl2(wrapper); VoidScriptMethodWrapper<Script> methodWrapper3 = new MethodWrapperImpl3(wrapper);We can now install the Script:
File file = new File(<our script file>); wrapper.installScript(file);And now we can run all the three methods:
int value = methodWrapper.executeMethod(); // value is 10 int value = methodWrapper2.executeMethod(1, 2); // value is 3 methodWrapper3.executeMethod(); // the message "I am here" is printed on the consoleAs you see, if we try do do:
int value = methodWrapper2.executeMethod(1f, 2f);The method will throw an exception, because the arguments are not identical to those defined in
MethodWrapperImpl2
. The next tutorial will explain how to cast automatically the arguments.Copyright 2019-2020 Herve Girod. All Rights Reserved. Documentation and source under the BSD licence