1、定义Java接口包含在Java中需要调用的Groovy方法
public interface IFoo {
public Object run(Object foo);
}
2、创建Groovy类实现该接口
class Foo implements IFoo {
public Object run(Object foo) {
println 'Hello World!'
x = 123
foo * 10
}
}
3、动态载入Groovy类,创建接口实例,调用接口中定义的方法
import groovy.lang.GroovyClassLoader;
import java.io.File;
public class InvokeGroovy {
public static void main(String[] args) {
ClassLoader cl = new InvokeGroovy().getClass().getClassLoader();
GroovyClassLoader groovyCl = new GroovyClassLoader(cl);
try {
Class groovyClass = groovyCl.parseClass(new File("src/Foo.groovy"));
IFoo foo = (IFoo) groovyClass.newInstance();
System.out.println(foo.run(new Integer(2)));
} catch (Exception e) {
e.printStackTrace();
}
}
}