Tôi gặp sự cố với thừa kế trong tập lệnh Groovy. Tôi muốn kịch bản Groovy của tôi kế thừa các phương thức từ lớp Java mà tôi gọi kịch bản lệnh này.Java + Groovy Script - Thừa kế
Ví dụ, tôi có một cái gì đó như thế này:
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";
}
}
Và lỗi này là:
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
Làm thế nào tôi có thể làm điều này nếu tôi không thể thừa kế bất kỳ lớp khác? Tôi muốn gọi phương thức chỉ giống như từ siêu lớp.
Sửa
tôi đã thay đổi lớp học của tôi để một cái gì đó như thế này:
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()");
}
}
}
Bây giờ lỗi là:
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) ...
vì ở trên là câu trả lời cho câu hỏi ban đầu mà tôi vừa thêm ở đây: 'com.test.SimpleTest $ GroovyHandler' cho biết rằng lớp cơ sở kịch bản của bạn là lớp bên trong và tôi giả sử nó không phải là một lớp bên trong tĩnh. Java sẽ không thêm một hàm tạo parameterless trong trường hợp đó, vì lớp bên trong cần phải lấy cá thể lớp bên ngoài. Vì vậy, chỉ cần làm cho lớp tĩnh và tất cả đều ổn – blackdrag