Java Reference
In-Depth Information
Roll Your Own Scripting Engine
Problem
You like javax.script but there isn't yet a script engine for your favorite language.
Solution
Roll your own: implement ScriptEngine and ScriptEngineFactory and add one trivial
configuration file.
Discussion
Hooking into an existing Scripting language sounds easy. It may or may not be, depending
on the language. Before you do implement one, check the set of languages available at Java's
website .
ScriptEngine is a fairly simple interface, with just over a dozen methods, of which six are
overloads of the popular eval method. There is an AbstractScriptEngine that handles all
these overloads and some other bookkeeping, leaving only four abstract methods. When you
extend AbstractScriptEngine , you only are required to implement four methods:
public
public class
class CalcScriptEngine
CalcScriptEngine extends
extends AbstractScriptEngine {
private
private ScriptEngineFactory factory ;
CalcScriptEngine ( ScriptEngineFactory factory ) {
super
super ();
this
this . factory = factory ;
}
@Override
public
public Object eval ( String script , ScriptContext context )
throws
throws ScriptException {
System . out . println ( "CalcScriptEngine.eval(): Running: " + script );
Stack < Integer > stack = new
new Stack <>();
StringTokenizer st = new
new StringTokenizer ( script );
while
while ( st . hasMoreElements ()) {
String tok = st . nextToken ();
iif ( tok . equals ( "+" )) {
Search WWH ::




Custom Search