December 28, 2006

Scripting in Java

The latest version of java brings a number of new features and enhancements that will improve the development of software in java platform. One new feature is the Scripting support that the new JDK will provide and this article is just the basics of it.

Most developers know scripting languages like Perl,PHP,Python,Ruby and some are crazy about it because they are simple,flexible and highly productive. Java now comes with built-in support for scripting languages. This has been encoprated through Java Specification Request (JSR) 223, which defines a framework and provide the necessary API required to access and control the scripting environment, create web content with scripting and embed scripting technology in java based applications.

So the start with, we have a script engine that helps us in executing the script and our first step would be to import some packages. The classes and interfaces required are defined in the package javax.script. The main class is ScriptEngineManager which is the script engine that executes the scripts. So we have it instantiate it as our second step. So the simple steps for incoprating scripting will be:

1) Create an instance of ScriptEngineManager.
2) Get the required scripting engine.
3) Execute the script using the scripting engine.

The first two steps are as follows:

ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("JavaScript");

So now you have the engine to run java scripts. To execute a script we have to use the eval API which is in ScriptEngine.
To execute (evaluate) a script we have:

engine.eval("script to run");

One thing to remeber is eval method return an Object and we have many overloaded versions of eval. These are not the only features, we can invoke procedures using the Invocable interface. To invoke a procedure we use invokeFunction or invokeMethod methods.

So that's all about scripting for now. For reference check the tutorials provided in java site and also check the javadocs.

No comments :