我在Groovy脚本中遇到了继承问题。我希望我的Groovy脚本可以从我调用此脚本的Java类中继承方法。
例如,我有如下代码:
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";
}
}
错误信息如下:
org.codehaus.groovy.control.MultipleCompilationErrorsException: 启动失败: Script1.groovy: 1: 声明类型 com.test.SimpleTest 并没有继承 groovy.lang.Script 类! @ line 1, column 1. println sayHello() ^ 1 error
如果我不能继承其他类,怎么办呢?我想像从超类那样调用方法。
编辑
我把我的类改成了这样:
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()");
}
}
}
现在的错误是:
java.lang.NoSuchMethodError: com.test.SimpleTest$GroovyHandler:找不到方法< init >()V at Script1.(Script1.groovy) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at java.lang.Class.newInstance0(Class.java:355) at java.lang.Class.newInstance(Class.java:308) at org.codehaus.groovy.runtime.InvokerHelper.createScript(InvokerHelper.java:429) at groovy.lang.GroovyShell.parse(GroovyShell.java:704) at groovy.lang.GroovyShell.evaluate(GroovyShell.java:588) at groovy.lang.GroovyShell.evaluate(GroovyShell.java:627) at groovy.lang.GroovyShell.evaluate(GroovyShell.java:598) ...
com.test.SimpleTest$GroovyHandler
表示您的脚本基类是一个内部类,我假设它不是静态内部类。在这种情况下,Java 不会添加无参数构造函数,因为内部类需要获取外部类实例。所以只需将该类设置为静态即可解决问题。 - blackdrag