首页 > 代码库 > 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动态解析
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。