Scripting in Java 6.0 - Part 1
by Krishna Srinivasan
11/02/2007
Introduction
In this article i will write a small program using Scripting feature in Java 6.0, a new feature introduced in Java 6.0 mustang. This is cool and more useful when we are working with the scripting languages. I am not going to explain in depth, will explain with very small example. In my next article i will write about the advanced features in script programming in java. Follow the steps to run your first script program in Java 6.0 :
Setting Environments
- download and Install Java 6.0 from sun site
- download Rhino script engine from Mozilla site
- Get the js.jar file from the package and add into the classpath
Note : js.jar file is script engine implementation for JavaScript. It should be in the classpath when you are running
the example program
Writing HelloWorld.js
function testMessage(msg){
print("Printing : " + msg);
}
Writing HelloWorld.java
New package javax.script is added to the java 6.0 version. It provides necessary APIs to work with script engines. Sun's implementation of JDK 6 is co-bundled with the Mozilla Rhino based JavaScript script engine.
import javax.script.*;
class HelloWorld{
public static void main(String args[]) throws Exception{
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
engine.eval(new java.io.FileReader("helloworld.js"));
Invocable inv = (Invocable) engine;
inv.invokeFunction("testMessage", "Hello World!!!" );
}
}
Run the application
type in the command prompt
>> javac HelloWorld.java
>> java HelloWorld
Will be printed as :
Printing : Hello World!!!
In my next article i will explain how scripting works with java and how it is implemented.
|
|
Bookmark This Page :
|
|