Groovy動態解析

獵手家園發表於2017-05-03

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);

 

相關文章