使用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。
本文介绍了一个使用GroovyShell动态编译Groovy代码的示例。通过控制台输入两段Groovy代码,一段定义函数,另一段调用该函数进行计算并输出结果。
559

被折叠的 条评论
为什么被折叠?



