首页 > 代码库 > Groovy动态解析

Groovy动态解析

A:前面需要说些什么吗?

B:不需要吗?

A:需要吗?

 

解析方式一:通过指定的paths来初始化GroovyScriptEngine

//通过指定的paths来初始化GroovyScriptEngineString[] 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来初始化GroovyScriptEngineString[] 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动态解析