我在这里有一个Groovy课程:
Plus.groovy
def add = { int x, int y ->
return x+y
}
我们如何在Groovy或Java中使用它,如'Plus.add(5,6)',结果是11
由于
答案 0 :(得分:0)
我不确定你在这里想要实现什么,你在问你如何在Groovy中使用这个方法吗?给出以下类定义
class Plus {
def add(def x, def y) {
return x + y;
}
}
// assert test
assert 4 == new Plus().add(2, 2)
答案 1 :(得分:0)
我找到了解决方案。使用Binding和GroovyShell。
Binding binding = new Binding();
GroovyShell shell = new GroovyShell(binding);
try {
Object value = shell
.evaluate("com.groovy.Plus plus = new com.groovy.Plus (); return plus.add(5,6;");
System.out.println(value);
} catch (Exception e) {
System.out.println("exception : " + e);
}