pom
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.3</version>
</dependency>
Java接口:
public interface Run {
public void speed(int s);
}
Groovy实现类:
class TomRun implements Run{
@Override
void speed(int s) {
println 'I m tom running '+s
}
}
Java客户端加载groovy文件调用:
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import java.io.File;
public class ClientRun {
public static void main(String[] args) {
try {
GroovyClassLoader loader= new GroovyClassLoader();
//把groovy放在E盘或是随便一个目录下
Class groovyClass =loader.parseClass(new File("E:\\TomRun.groovy"));
GroovyObject object =(GroovyObject) groovyClass.newInstance();
Run r = (Run)object;
r.speed(1000);
//定期清除ThreadGroupContext中的缓存后,实现了对Groovy加载类的垃圾回收,避免出现OOM的问题
Introspector.flushCaches();
loader.clearCache();
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果
正常调用,无需编译,运行时加载groovy文件