Java Cookbook Recipe 26.x - Calling All Languages - from javax.script

Problem

You want to invoke a script written in some other language from within your Java program.

Solution

If the script you want is written in any of the two-dozen-plus supported languages, just use javax.script. Languages include awk, perl, python, Ruby, BeanShell, PNuts, Ksh/Bash, several implementations of JavaScript, and many more. To see the full list of languages, and download the "script engines" - the interfaces fom Java to each of the languages - visit http://scripting.dev.java.net.

Discussion

... details ...

ScriptEnginesDemo lists the installed engines, and runs a simple script in the Java6 default language, ECMAScript (aka JavaScript).

package scripting;

import java.util.List;

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

public class ScriptEnginesDemo {

	public static void main(String[] args) throws ScriptException {
		ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
		
		// Get list of supported languages
		List engineFactories = 
			scriptEngineManager.getEngineFactories();
		for (ScriptEngineFactory fact : engineFactories) {
			System.out.println(fact.getLanguageName());
		}
		
		// Run a script in the default language
		String lang = "ECMAScript";
		ScriptEngine engine = 
			scriptEngineManager.getEngineByName(lang);
		if (engine == null) {
			System.err.println("Could not find engine");
			return;
		}
		engine.eval("print(\"Hello from " + lang + "\");");
	}
}

Synch Notes

This impinges on 26.4 "Marrying Java and Perl", which will be cut in half to become "Calling Java from Perl". Maybe move the "Perl from Java" part of it here.