Rapid Java Application Development with Javascript

Since the advent of Java 6, the Scripting capability has been one of the most beautiful thing that has been added to Java. Now you don’t need to know full Java to make parts of your application. You can externalise code so that parts of your application can be written in scripting language and then you can dynamically edit the scripts to change the behaviour of the application without going through the complicated task of compiling the full application once again!

The scripting languages have some definite advantages over a full fledged programming language :

  • Convenience: Most scripting languages are dynamically typed. You can usually create new variables without declaring the variable type, and you can reuse variables to store objects of different types. Also, scripting languages tend to perform many type conversions automatically, for example, converting the number 10 to the text “10” as necessary.
  • Developing rapid prototypes: You can avoid the edit-compile-run cycle and just use edit-run and save yourself from a bit of extra work!
  • Application extension/customization: You can “externalize” parts of your application – like configuration scripts, business logic/rules and math expressions for financial applications. You can let your team write certain plugins or codes that will add extra functionality to your application.
  • “Command line” shells for applications -Many a times we prefer command line tools. Instead of inventing ad-hoc scripting language for that purpose, a “standard” scripting language can be used.

The default Javascript engine thats ships with Java does a pretty good job.  You can do a couple pretty simple tasks that will help you build your application’s logic fast without delving into the minute details implementing it in the core programming language. You don’t need to spend time datatypes, methods, or even classes. You can jump right away to your programs logic and then begin coding.

I’ll just take a basic example over here. Lets create a simple GUI window because most of just like shiny buttons and windows! First we’ll write our general purpose interpreter of our Javascript files, that will execute our scripts. Just write the following code and save it as RunScript.java

import javax.script.*;
class RunScript{
 public static void main(String args[]) throws Exception{
 ScriptEngineManager factory=new ScriptEngineManager();
 ScriptEngine engine=factory.getEngineByName("JavaScript");
 engine.eval(new java.io.FileReader("script.js"));
 }
}

This file will always execute script.js in the current directory. Now compile this file.

Next up we will write our Javascript code and save it as script.js

//first we'll import the packages
importPackage(javax.swing);
importPackage(java.awt);
//we'll declare the objects required. notice that there are no explicitly declared types for the variables
var frame=new javax.swing.JFrame("Hello");
var button=new javax.swing.JButton("I'm a button!");
//these are normal method callings on the objects that we used to do in java
frame.setSize(500,200);//setting the window size to be 500x200
frame.setLayout(new java.awt.FlowLayout());//setting up the layout manager for our window
frame.add(button);//adding the button to our window
frame.setVisible(true);//making the window visible
println("I'm done!");//printing on the terminal that we're done

After saving this file, run the program RunScript. It will create a new window for you with a button on it saying I’m a button! . That was damn easy. No need of worrying about datatypes in the variables. We just go about creating variables ad-hoc when necessary, instantiating it at that moment.

Just to see another advantage, change the following line

var button=new javax.swing.JButton("I'm a button!");

to the following line

var button=new javax.swing.JButton("I've changed!");

And then run the program RunScript. Yep! No need to compile just run it! Your button just changed on screen!

Variables don’t have explicit datatypes associated means we can modify them to suit our need when we want. The following example will just show:

value=5;
println(value+2);
value="Hello World";
println(value);

Here first we have value behaving as an integer. We can perform arithmetic operations as show above. Immediately after that we can change that same variable  value to become a string. We can change datatypes during runtime.

What this means is that we can focus solely on our application’s logic before we go into the intricacies of actually implementing it fully in Java. Once we have developed the minimal application with its full working logic in place we can move it into a Java code or for that matter run the script directly as well. We can even let others design scripts that can be added at runtime extend the functionality of our programs. But needless to say if your keeping your final code in this script form for large, complicated applications where code can better organised into classes is not very productive. In such cases its suitable for prototyping of your applications where you implement your application’s logic via script.

This just scratches the surface. you can further integrate this with Java to access the classes, interfaces and objects from Java to Javascript and vice-versa. You can even implement this in other scripting languages apart from Javascript as well. For more details look at http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/

2 thoughts on “Rapid Java Application Development with Javascript

  1. Dear Sir,
    Your work is very impressive. It is excellent. I tried them, and they worked. The examples you have shown are to execute a javascript from Java. Is there an example that you could give so that a Java compiled .class could be executed in a javascript function (called from the javascript) ? (i.e. a reverse process). Many thanks. With Regards, Kim

    1. thanks.. 🙂

      You can execute code java .class files. Make sure you have them in your classpath. And then any sample code like this could work in javascript:

      importClass(mypackage.MyClass);
      var obj=new mypackage.MyClass();
      obj.myMethod();

      Then you can run this javascript from the inbuilt scripting engine in java.

Leave a comment