Eclipse Wiki Weblog

All | General | Java | Eclipse | Wikipedia | AJAX(GWT)
20060504 Thursday May 04, 2006

MathEclipse Scripting Engine (JSR 223)

Für das MathEclipse Projekt [1] habe ich eine zu JSR 223 kompatible Scripting Engine [2] erstellt. Diese Scripting Engine basiert auf dem Java Scripting Framework, das ab Java Version 6.0 im JDK mit enthalten ist.

Das folgende Snippet berechnet z.B. die Ableitung von Sin[x]:

	public static void main(String[] args) {
		ScriptEngineManager scriptManager = new ScriptEngineManager();

		String stringResult = null;
		ScriptEngine meEngine = scriptManager.getEngineByExtension("m");
		try {
			stringResult = (String) meEngine.eval("D[Sin[x],x]");
			System.out.println(stringResult);
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

Variablen können aus Java heraus mit Werten "vorbelegt" werden:

		try {
			meEngine.put("x", new Boolean(true));
			meEngine.put("y", new Boolean(true));
			stringResult = (String) meEngine.eval("x && y");
                        // prints True
			System.out.println(stringResult);
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

Durch die java.io.Reader Unterstützung in der ScriptEngine#eval() Methode, kann ein Script auch sehr einfach aus einer Datei heraus geladen und ausgeführt werden. Die folgende Matrix-Multiplikation zeigt einige Möglichkeiten der Parameterübergabe an die ScriptEngine

		try {
			ArrayList row = new ArrayList();
			row.add("List"); // head of the expression
			row.add(Integer.valueOf(1));
			row.add(Integer.valueOf(2));
			row.add(Integer.valueOf(3));

			int[] intArr = { 3, 4, 11 };

			meEngine.put("x", row);
			meEngine.put("y", intArr);
			// the test.m file contains this script:
			// $m={x, y, {13, 7, 8}};
			// $m.$m

			ScriptContext context = meEngine.getContext();
			context.setAttribute(MathScriptEngine.RETURN_OBJECT, Boolean.TRUE,
ScriptContext.ENGINE_SCOPE);
			Object objectResult = meEngine.eval(new 
FileReader("C:\\eclipse\\workspace\\org.matheclipse.script\\test.m"));
			// print result for this matrix multiplication
			// {{1,2,3}, {3, 4, 11}, {13, 7, 8}}.{{1,2,3}, {3, 4, 11}, {13, 7, 8}}
			System.out.println(objectResult.toString());
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
Posted by axelclk ( May 04 2006, 08:08:13 PM CEST ) Permalink Comments [0]

Kalender

Links

del.icio.us Tag Cloud

RSS Feeds

Suche

Navigation

Referenziert von