1.maven引入groovy jar包
org.codehaus.groovy
groovy-all
2.1.9
2.调用
package com.test;
import java.util.ArrayList;
import java.util.List;
import groovy.lang.GroovyShell;
public class TestGroovy {
public static void main(String[] args) {
// TODO Auto-generated method stub
long l1 = System.currentTimeMillis();
GroovyShell groovyShell = new GroovyShell();
System.out.println(System.currentTimeMillis()-l1);//new一个groovy对象时间好像有点久 100多毫秒
long l2 = System.currentTimeMillis();
TestGroovy t = new TestGroovy();
System.out.println(System.currentTimeMillis()-l2);
Object resultObj;
int x = 1;
groovyShell.setVariable("x", 3);//注册变量值
List list = new ArrayList();
groovyShell.setVariable("list", list);//注册变量值
resultObj = groovyShell.evaluate("import com.test.TestGroovy;TestGroovy.sys(''+x);list.add('xxxx');x=4; x<1;"); //groovy执行 、还可以import java类进行调用 groovy默认返回最后一行的执行结果
System.out.println(resultObj);
System.out.println(x);//groovy没有改变x的值
System.out.println(list);//groovy 改变了list的值
resultObj = groovyShell.evaluate("import com.test.TestGroovy;TestGroovy.sys(''+x)"); //之前设置的x值还在 x=4;
}
public static void sys(String s){
System.out.println(s);
}
}