I have a problem with inheritance in a Groovy script. I want my Groovy script to inherit methods from the Java class that I call in this script.
For example, I have something like this:
public class SimpleTest extends TestCase { public void test(){ CompilerConfiguration configuration = new CompilerConfiguration(); configuration.setScriptBaseClass(this.getClass().getName()); GroovyShell shell = new GroovyShell(this.getClass().getClassLoader(), new Binding(), configuration); shell.evaluate("println sayHello()"); } public String sayHello(){ return "Hello"; } }
And the error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script1.groovy: 1: Declared type com.test.SimpleTest does not extend the groovy.lang.Script class! @ row 1, column 1. println sayHello () Error ^ 1
How to do this if I cannot inherit any other class? I want to call the method only as from a superclass.
Edit
I changed my class to something like this:
public class CmTest extends TestCase { public void test(){ GroovyHandler handler = new GroovyHandler(); handler.run(); } public String sayHello(){ return "Hello"; } public class GroovyHandler extends Script { public GroovyHandler(){ } @Override public Object run() { CompilerConfiguration configuration = new CompilerConfiguration(); configuration.setScriptBaseClass(this.getClass().getName()); GroovyShell shell = new GroovyShell(CmTest.class.getClassLoader(), new Binding(), configuration); return shell.evaluate("println sayHello()"); } } }
Now the error:
java.lang.NoSuchMethodError: com.test.SimpleTest $ GroovyHandler: method <init> () V not found in Script1. (Script1.groovy) at sun.reflect.NativeConstructorAccessorImpl.newInstance0 (native method) at sun.reflect.NativeConstructorAccessorImpl.newInstance (NativeConstructorAccessorImpl.java:39) on sun.reflect.DelegatingConstructorAccessorImplon. instructorAccessorImstructor.ccessor lang.reflect.Constructor.newInstance (Constructor.java∗13) in java.lang.Class.newInstance0 (Class.javahaps55) in java.lang.Class.newInstance (Class.java:308) at org.codehaus.groovy .runtime.InvokerHelper.createScript (InvokerHelper.java:429) in groovy.lang.GroovyShell.parse (GroovyShell.java:704) in groovy.lang.GroovyShell.evaluate (GroovyShell.javahaps88) in groovy.lang.rogro. evaluate (GroovyShell.java:627) in groovy.lang.GroovyShell.evaluate (GroovyShell.java∗98) ...
mhuta source share