欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java中加载Groovy文件及调用其方法 博客分类: Groovy Groovy 

程序员文章站 2024-03-24 21:52:22
...

本例中,我们会使用GroovyClassLoader来加载groovy脚本。

GroovyClassLoader是一个定制的类装载器,负责解释加载Java类中用到的Groovy类。它也能编译。清单2.21展示了如何使用GroovyClassLoader加载Groovy类并且调用该类的一个方法。

@Component
public class AccessComputeService {

    public static final Logger logger = LoggerFactory.getLogger(AccessComputeService.class);

    private static GroovyClassLoader loader;

    private static final ConcurrentHashMap<String,GroovyObject> groovyObjects = new ConcurrentHashMap<>();

    static {
        PathMatchingResourcePatternResolver resolver = new  PathMatchingResourcePatternResolver();
        loader = new GroovyClassLoader(AccessComputeService.class.getClassLoader());
        try {
            //适配读取classpath下面的*.groovy文件列表
            Resource[] resources = resolver.getResources("classpath:accessScore/*.groovy");
            if(resources==null || resources.length==0){
                logger.warn("未获取到groovy文件");
            }else{
                for (Resource resource: resources) {
                    try ( InputStream inputStream = AccessComputeService.class.getClassLoader().getResourceAsStream("accessScore/" + resource.getFilename())){
                        logger.info("加载准入评分groovy脚本:{}", resource.getFilename());
                        String text = CharStreams.toString(new InputStreamReader(inputStream, "UTF-8"));
                        Class groovyClass = loader.parseClass(text,resource.getFilename());
                        GroovyObject scriptInstance = (GroovyObject)groovyClass.newInstance();
                        groovyObjects.put(resource.getFilename().split("\\.")[0],scriptInstance);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("groovy 引擎初始化失败!!!!!!!!",e);
        }
    }

    public void execute(String scriptFileName, String scriptFunctionName, Map<String, Object> dataMap) {
        //scriptFileName:文件名,scriptFunctionName:文件的方法,dataMap:参数
        Strong result = (String)groovyObjects.get(scriptFileName).invokeMethod(scriptFunctionName, dataMap);
    }
}

 

其他调用groovy的方式

http://blog.csdn.net/eric_sunah/article/details/11541307

相关标签: Groovy