java调用、执行groovy代码

 1: package test;
 2:  
 3: import javax.script.ScriptEngine;
 4: import javax.script.ScriptEngineManager;
 5: import javax.script.ScriptException;
 6:  
 7: public class ScriptExcuteUtil {
 8:  
 9:     public ScriptExcuteUtil() {
 10:  
 11:     }
 12:  
 13:     /**
 14:  * @param args
 15:  */
 16:     public static void main(String[] args) {
 17:         ScriptEngineManager manager = new ScriptEngineManager();
 18:         ScriptEngine engine = manager.getEngineByName("groovy");
 19:         try {
 20:             System.out.println("calling groovy from java start");
 21:             engine.put("name", "VerRan");
 22:             engine.eval("println \"${name}\"+\"你好\";name=name+'!'");
 23:             System.out.println(engine.get("name"));
 24:             System.out.println("calling groovy from java end");
 25:             
 26:             engine.eval("");
 27:         } catch (ScriptException e) {
 28:             e.printStackTrace();
 29:         }
 30:     }
 31:  
 32: }
 
 
 1: package test;
 2:  
 3: import groovy.lang.GroovyClassLoader;
 4: import java.io.File;
 5:  
 6: public class InvokeGroovy {
 7:     public static void main(String[] args) {
 8:         ClassLoader cl = new InvokeGroovy().getClass().getClassLoader();
 9:         GroovyClassLoader groovyCl = new GroovyClassLoader(cl);
 10:         try {
 11:             // 从文件中读取
 12:             Class groovyClass = groovyCl.parseClass(new File(
 13:                     "C:\\mysource2\\GroovyLearn\\groovy\\fist\\Foo.groovy"));
 14:             Class groovyClass2 = groovyCl
 15:                     .parseClass("package org.openjweb.groovy; \r\n import test.IFoo;\r\n class Foo implements IFoo {public Object run(Object foo) {return ((Integer)foo).intValue()+3}}");
 16:  
 17:             IFoo foo = (IFoo) groovyClass.newInstance();
 18:             System.out.println(foo.run(new Integer(2)));
 19:  
 20:             IFoo foo2 = (IFoo) groovyClass2.newInstance();
 21:             System.out.println(foo2.run(new Integer(2)));
 22:  
 23:         } catch (Exception e) {
 24:             e.printStackTrace();
 25:         }
 26:     }
 27: }
ClassLoader 的另一种方式

ClassLoader parent = ClassLoader.getSystemClassLoader();

GroovyClassLoader loader = new GroovyClassLoader(parent);

你可能感兴趣的:(groovy)