我在 Java class
中使用 Groovy Interpreter,我正在尝试定义一个方法并调用它,这是我的代码:
Binding binding = new Binding();
binding.setVariable("aa", 1);
binding.setVariable("bb", 2);
GroovyShell shell = new GroovyShell(binding);
shell.evaluate("int add(int a,int b){return (a+b)}");
int value =(int) shell.evaluate("add(aa,bb);");
System.out.println(value);
我遇到了这个错误:
Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: Script2.add() is applicable for argument types: (java.lang.Integer, java.lang.Integer) values: [1, 2] Possible solutions: any(), wait(), run(), run(), find(), wait(long, int)
请告诉我如何在 groovy 中定义一个函数,以及为什么我的代码不起作用。
最好的问候,
最佳答案
当您使用 GroovyShell#evaluate
时,shell 将整个脚本编译成 JVM 类,加载并运行它,然后返回结果。这个过程对于每个 evaluate
调用都是独立的(注意类的名称是 Script2
;方法是在 Script1
中定义的),所以您的方法在第二次调用中不可用。
解决此问题的选项包括在评估之前简单的字符串连接(这适用于您自己的脚本,但如果脚本中的某些内容调用 return
可能会出现问题)或使用更复杂的 GroovyScriptEngine
.
关于java - 在 Java 中使用的 Groovy 中定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47120396/