使用Groovy编程的最大的特点是:在jvn运行时,动态的编译Groovy代码。下面我们通过一个简单的实例验证这个奇特的功能。代码如下:
import groovy.lang.GroovyShell;
import groovy.lang.Script;
/**
* @author liuhongbo
*
*/
public class TestGroovyShell {
public static void test(String[] args) {
GroovyShell shell = new GroovyShell();
//String scriptText = "def mul(x, y) { x * y }\nprintln mul(5, 7)";
String scriptText = args[0] + "\n" + args[1];
Script script = shell.parse(scriptText);
Object result = script.run();
}
public static void main(String[] args) {
test(args);
}
}
通过程序的代码我们可以看出,在控制台要输入两个参数,参数的内容是 Groovy 代码。代码内容如下:
"def mul(x, y) { x * y } " "println mul(5, 10)"
Eclipse 配置如下:
运行结果输出:50。