JavaFX z Arią - powrót do strony głównej

Ewaluacja skryptu z użyciem ScriptContext

Klasa E07_EvalSciptWithContext.java
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 E07_EvalScriptWithContext {
	public static void main(String[] args) {
		//ScriptContext ctx = new SimpleScripContext();
		SimpleScriptContext ctx = new SimpleScriptContext();
		ctx.setAttribute("a", 125, ScriptContext.ENGINE_SCOPE);
		ctx.setAttribute("b", 4, ScriptContext.ENGINE_SCOPE);

		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, ctx);
		}
		catch (IOException | ScriptException e) {
			e.printStackTrace();
		}
	}
}
Skrypt
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;
}