我在 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 类!@ 第 1 行,第 1 列。 println sayHello() ^ 1 错误
如果我不能继承任何其他类,我该怎么做?我只想像从超类一样调用方法。
编辑
我把我的班级改成这样:
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:在 sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 在 sun.reflect.NativeConstructorAccessorImpl 的 Script1.(Script1.groovy) 找不到方法 < init >()V。 newInstance(NativeConstructorAccessorImpl.java:39) 在 sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) 在 java.lang.reflect.Constructor.newInstance(Constructor.java:513) 在 java.lang.Class.newInstance0(Class .java:355) 在 java.lang.Class.newInstance(Class.java:308) 在 org.codehaus.groovy.runtime.InvokerHelper.createScript(InvokerHelper.java:429) 在 groovy.lang.GroovyShell.parse(GroovyShell. java:704) 在 groovy.lang.GroovyShell.evaluate(GroovyShell.java:588) 在 groovy.lang.GroovyShell。在 groovy.lang.GroovyShell.evaluate(GroovyShell.java:598) 处评估(GroovyShell.java:627) ...