Groovy动态解析
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Groovy动态解析相关的知识,希望对你有一定的参考价值。
A:前面需要说些什么吗?
B:不需要吗?
A:需要吗?
解析方式一:通过指定的paths来初始化GroovyScriptEngine
//通过指定的paths来初始化GroovyScriptEngine String[] paths = {"D:\\GroovyScript"}; GroovyScriptEngine gse = new GroovyScriptEngine(paths); Binding binding = new Binding(); binding.setVariable("input", "world"); gse.run("GroovyDemo.groovy", binding); System.out.println(binding.getVariable("output"));
GroovyDemo.groovy
output = "Hello ${input}!"
解析方式二:通过指定的roots来初始化GroovyScriptEngine
//通过指定的roots来初始化GroovyScriptEngine String[] roots = new String[]{"src/com/ccav/javarisk/"}; GroovyScriptEngine gsen = new GroovyScriptEngine(roots); GroovyObject groovyObject = (GroovyObject) gsen.loadScriptByName("HelloWorld.groovy").newInstance(); String result = (String) groovyObject.invokeMethod("output", "world"); System.out.println(result);
HelloWord.groovy
class TestScript { static String output(def str) { return "Hello " + str + ", I‘m first!"; } }
解析方式三:创建engine实例直接解析文本内容
//创建engine实例直接解析文本内容 ScriptEngineManager factory = new ScriptEngineManager(); //每次生成一个engine实例 ScriptEngine engine = factory.getEngineByName("groovy"); System.out.println(engine.toString()); assert engine != null; Bindings binding = engine.createBindings(); binding.put("date", new Date()); //如果script文本来自文件,请首先获取文件内容 engine.eval("def getTime(){return date.getTime();}", binding); engine.eval("def sayHello(name,age){return ‘Hello,I am ‘ + name + ‘,age‘ + age;}"); Long time = (Long) ((Invocable) engine).invokeFunction("getTime", null); System.out.println(time); String message = (String) ((Invocable) engine).invokeFunction("sayHello", "zhangsan", new Integer(12)); System.out.println(message);
以上是关于Groovy动态解析的主要内容,如果未能解决你的问题,请参考以下文章
GroovyGroovy 脚本调用 ( Groovy 配置文件格式 | Groovy 配置文件读取 | 完整配置文件及解析代码示例 )