Java + Groovy脚本 - 继承

时间:2015-05-21 12:49:47

标签: java inheritance groovy groovyshell

我在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:method< init>()V未找到       在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)       在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.evaluate(GroovyShell.java:627)       at groovy.lang.GroovyShell.evaluate(GroovyShell.java:598)...

2 个答案:

答案 0 :(得分:0)

将在脚本中使用的类必须扩展Script

示例:

class ScriptTest extends Script {
    def SayHello() {
        return "Hello"
    }
}

然后你setScriptBaseClass到这个特定的班级

答案 1 :(得分:0)

我已经解决了我的问题。解决方案是DelegatingScript类。 链接到doc: http://docs.groovy-lang.org/latest/html/gapi/groovy/util/DelegatingScript.html