Java - ScriptEngine

From XennisWiki
Jump to: navigation, search

JavaScript

String

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;


public class Java2Script {
	
	public static void main(String[] args) {
	
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("javascript");
		engine.put("a", 10);
		engine.put("b", 8);
		String script = "var result = Math.min(a, b);";
		
		System.out.println(compute(engine, script, "result"));
	}
	
	/**
	 * Gibt das Ergebnis des Scripts zurück.
	 * 
	 * @param engine Script engine
	 * @param script Script als String
	 * @param get Get als String
	 * @return Ergebnis als Object
	 */
	public static Object compute(ScriptEngine engine, String script, String get) {
		Object result = null;
		try {
			engine.eval(script);
			result = engine.get(get);
		} catch (ScriptException e) {
			e.printStackTrace();
		}
		return result;
	}

}

Datei

import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;


public class Java2Script {
	
	public static void main(String[] args) {
	
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("javascript");

		System.out.println(compute(engine, "test.js", "result"));
	}
	
	/**
	 * Gibt das Ergebnis des Scripts zurück.
	 * 
	 * @param engine Script engine
	 * @param fileName JavaScript Datei
	 * @param get Get als String
	 * @return Ergebnis als Object
	 */
	public static Object compute(ScriptEngine engine, String fileName, String get) {
		Object result = null;
		try {
			FileReader script = new java.io.FileReader(fileName);
			engine.eval(script);
			result = engine.get(get);
		} catch (ScriptException | FileNotFoundException e) {
			e.printStackTrace();
		}
		return result;
	}
}

test.js

var a = 10;
var b = 8;
var result = Math.min(a, b);

External links