Java Reference
In-Depth Information
Of course, most scripts need parameters or “variables” passed in. The scripting demo imple-
ments the most trivial calculator, a four-function stack-based (“reverse Polish notation”) in-
teger calculator. Just enough to show that values are getting in and the value back out. For
example, if the script input is
+i j *+
that is an instruction to get the values i and j and multiply them together. Then these vari-
ables' values have to be passed in before the script can execute successfully; that is the func-
tion of the
engine.put("i", 99);
engine.put("j", 1);
in the demo program. The one eval() overload that's implemented puts numbers into a
stack and, when an operator is found, pops two values off the stack and performs one of the
four basic operators that are implemented, and stacks and returns the value. Obviously it's
not usable for anything at this stage, but it shows the mechanism for getting values in and
out. Oh, and it gets the correct answer:
CalcScriptEngine.eval(): Running: i j +
Script returned 100
As an advanced feature, if you are writing an engine for a scripting language that supports
compiling scripts into some kind of saveable file format (as javac produces .class files, py-
thon produces .pyc , etc.) you should investigate the Compilable and Invocable interfaces.
This example can be run as part of the javasrc repository (see Downloading and Using the
Code Examples ) . It is typical, but not required, to bundle up the two classes and the config-
uration file into a separate JAR file for distribution (and ease of installation).
You now have the ability to include arbitrary languages into your Java application. Before
you do so, make sure there isn't already an implementation available, at the URL shown in
the introduction to this recipe!
Search WWH ::




Custom Search