我正在测试Groovy,但我无法弄清楚如何正确调用GroovyScriptEngine。它会在下面产生错误。
org.codehaus.groovy.runtime.metaclass.MissingMethodExceptionNoStack
Song.Groovy
class Song {
def args;
{
println "Song has been called." + args;
}
String getArtist(){
return "sdfsdf";
}
public String toString(){
return "Hey!";
}
}
Java Main - >
String[] paths = { "C:\\Users\\User\\workspace\\GroovyTest\\src\\groovy" };
GroovyScriptEngine gse = new GroovyScriptEngine(paths);
Binding binding = new Binding();
Object s = "Default...";
binding.setVariable("args", s);
gse.run("Song.groovy", binding);
args变量也会产生null ..
怎么办?
答案 0 :(得分:1)
你正在上课!
如果你想测试你的课程,请在Song.groovy的最后尝试这样的事情:
// Instantiate an object of your class and use some methods!
def song = new Song()
println song.getArtist();
运行时
gse.run("Song.groovy", binding);
你基本上正在加载你的课程,但你没有做任何事情。
请参阅此示例here
答案 1 :(得分:0)
(代表OP发布):
工作代码:
<强> Test1.java 强>
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
public class Test1 {
public static void main(String[] args) throws Exception {
String[] paths = { "C:\\Users\\User\\workspace\\GroovyTest\\src\\groovy" };
GroovyScriptEngine gse = new GroovyScriptEngine(paths);
Binding binding = new Binding();
binding.setVariable("args", "Test Data");
String result = (String) gse.run("File1.groovy", binding);
System.out.println("Groovy Result: " + result);
}
}
<强> File1.groovy 强>
package groovy;
class Greeter {
String sayHello(String data) {
def greet = data;
return greet
}
}
static void main(String[] args) {
def greeter = new Greeter()
return greeter.sayHello(args);
}