Ewaluacja skryptu z użyciem Bindings
Nasz projekt aktualnie wygląda tak:
Ewaluujemy skrypt z pliku używając metody ScriptEngine
Object eval(Reader script, Bindings bindings)
Klasa E05_EvalScriptWithBindings
package jsr223groovy; import javax.script.*; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class E05_EvalScriptWithBindings { public static void main(String[] args) { //Bindings params = new SimpleBindings(); SimpleBindings params = new SimpleBindings(); params.put("a", 125); params.put("b", 4); String fileName = "src/scripts/skrypt3.groovy"; Path path = Paths.get(fileName); if (! Files.exists(path) ) { System.out.println(path.toAbsolutePath() + " nie istnieje."); return; } ScriptEngineManager sem = new ScriptEngineManager(); ScriptEngine se = sem.getEngineByName("Groovy"); try { Reader reader = Files.newBufferedReader(path); se.eval(reader, params); } catch (IOException | ScriptException e) { e.printStackTrace(); } } }
Skrypt skrypt3.groovy
package scripts def dividing(int a, int b){ def a1 = a.intdiv(b) def a2 = a % b def res = [a1, a2] as int[] return res; } result = dividing(a,b) println("dividing($a, $b) = $result")
Po uruchomieniu klasy na konsoli zobaczymy:
dividing(125, 4) = [31, 1]
Klasa module-info.java
module jsr223groovy { requires org.apache.groovy; requires java.scripting; requires java.sql; }