我在 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: startup failed: Script1.groovy: 1: Declared type com.test.SimpleTest does not extend groovy.lang.Script class! @ line 1, column 1. println sayHello() ^ 1 error
如果我不能继承任何其他类,我该怎么办?我只想调用父类(super class)中的方法。
编辑
我把我的类(class)改成了这样:
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: method < init >()V not found 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) ...
最佳答案
将在脚本中使用的类必须扩展 Script
例子:
class ScriptTest extends Script {
def SayHello() {
return "Hello"
}
}
然后你setScriptBaseClass
到这个特定的类
关于Java + Groovy 脚本 - 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30374282/