需要将groovy-2.4.3.jar加入到classpath中

一:在java中用GroovyClassLoader执行groovy代码

CalculateMax.groovy

1 class CalculateMax{
2     def Integer getMax(List values){
3         values.max();
4     }
5 }
View Code

UseGroovyClassLoader.java

 1 package groovy_java_1;
 2 
 3 import java.io.File;
 4 import java.util.ArrayList;
 5 
 6 import groovy.lang.GroovyClassLoader;
 7 import groovy.lang.GroovyObject;
 8 
 9 public class UseGroovyClassLoader {
10     public static void main(String[] args){
11         GroovyClassLoader loader = new GroovyClassLoader();
12         try{
13             Class<?> groovyClass = loader.parseClass(new File("src/groovy_java_1/CalculateMax.groovy"));
14             GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance(); 
15             ArrayList<Integer> numbers = new ArrayList<Integer>();
16             numbers.add(new Integer(1));
17             numbers.add(new Integer(10));
18             Object[] arguments = {numbers};
19             Object value = groovyObject.invokeMethod("getMax", arguments);
20             assert value.equals(new Integer(10));
21             System.out.println(value);
22         }catch(Exception e){
23             e.printStackTrace();
24         }
25     }
26 
27 }
View Code

 

二:在java中用GroovyShell执行groovy代码

UseGroovyShell.java

 1 package groovy_java_0;
 2 
 3 import java.math.BigDecimal;
 4 
 5 import groovy.lang.Binding;
 6 import groovy.lang.GroovyShell;
 7 
 8 public class UseGroovyShell {
 9     public static void main(String[] args){
10         Binding binding = new Binding();
11         binding.setVariable("x", 2.4);
12         binding.setVariable("y",8);
13         GroovyShell shell = new GroovyShell(binding);
14         Object value = shell.evaluate("x+y");
15         assert value.equals(new BigDecimal(10.4));
16     }
17 
18 }
View Code

 

三:在java中用GroovyScriptEngine执行Groovy代码

Hello.groovy

1 def hellostatement = "hello ${name}"
View Code

UseGroovyScriptEngine.java

 1 package groovy_java_2;
 2 
 3 import groovy.lang.Binding;
 4 import groovy.util.GroovyScriptEngine;
 5 
 6 public class UseGroovyScriptEngine {
 7     public static void main(String[] args){
 8         try {
 9             String[] roots = new String[]{"src/groovy_java_2"};    //设置根目录
10             GroovyScriptEngine gse = new GroovyScriptEngine(roots);    //初始化引擎
11             
12             Binding binding = new Binding();
13             binding.setVariable("name", "Gweneth");
14             
15             Object output = gse.run("Hello.groovy", binding);
16             System.out.println(output);
17             assert output.equals("hello Gweneth");
18 
19         } catch (Exception e) {
20             // TODO: handle exception
21             e.printStackTrace();
22         }
23     }
24 
25 }
View Code