在groovy脚本中实现java中定义的抽象类或接口,java调用groovy脚本返回抽象类实例。
1、定义Java接口包含在Java中需要调用的Groovy方法
public abstract class AbstractFunction {
public abstract String generateExpress(String... strArray);
public abstract Object[] parseExpress();
public abstract Object call(Object... arguments);
}
2、创建Groovy类实现该接口
import com.alkaid.test.semantic.tool.AbstractFunction
class ThisFunction extends AbstractFunction {
@Override
String generateExpress(String... strArray) {
return null
}
@Override
Object[] parseExpress() {
return new Object[0]
}
@Override
Object call(Object... arguments) {
return "This is the TestMethod"
}
}
3、动态载入Groovy类,创建接口实例,调用接口中定义的方法
GroovyClassLoader classLoader = new GroovyClassLoader();
Class groovyClass = classLoader.parseClass(script);
try {
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
AbstractFunction function = (AbstractFunction)groovyObject;
String message = (String)function.call(null);
System.out.println(message);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}