The Java Javascript Engine

Articles —> The Java Javascript Engine

While Javascript and Java are as similar to each other as Car and Carpet, the java JDK comes packaged with a javascript engine that can evaluate javascript code. From with a java application, one can use the ScriptEngineManager class to grab an instance of the ScriptEngine:


ScriptEngineManager mgr = new ScriptEngineManager();

ScriptEngine engine = mgr.getEngineByName("JavaScript");

From there, the engine object can be used to evaluate javascript code. How might this be useful? Take for instance, the issue of parsing and operating on a mathematical expression, represented as a String in Java:

(49+3)/5

In Java, one would require complex code to parse and evaluate the math - however one can readily evaluate this expression with the javascript engine:


System.out.println(engine.eval("(49+3)/5"));

The code above can be further extended to create a very basic command line read-eval-print-loop (REPL) for javascript:


public static void main( String[] args ) throws Exception{

	

	Scanner scanner = new Scanner(System.in);

	ScriptEngineManager mgr = new ScriptEngineManager();

    ScriptEngine engine = mgr.getEngineByName("JavaScript");



    System.out.print("> ");

    String line = scanner.nextLine();

    while ( !line.equals("exit") ){

    	try{

    		Object result = engine.eval(line);

    		if ( result != null ){

    			System.out.print(result);

    			System.out.println();

    		}

    	}catch(Exception e){

    		System.err.println("Could not parse script: " + e.getMessage());

    	}

    	System.out.print("> ");

    	line = scanner.nextLine();

    }

}

Similar in usage to that provided by the JDK (jrunscript), the code above is a simple REPL for javascript from within Java. Although neither allow for multi-line scripting, one can write a script in an text file and use the load() function to load the script into the engine.

A usefule feature the Javascript engine has is that it can access the Java API:


var file = new java.io.File('myFile.txt');

print (file.getAbsolutePath() + "\n");

print (file.lastModified() + "\n");

print (file.exists() + "\n");

The above code accesses the File class from the J2SE package java.io and creates an instance of this class, and uses the methods of the class to print out certain information about the file (presuming it exists).

One last comment as to the usefulness of the Javascript engine: it could be used to give users of an application access to some type of front-end or back-end scripting of the application, allowing the users to automate processing within a particular application. As an example, consider a photo catalog application - a scripting feature similar to the javascript engine could provide users a powerful way to move, rename, and/or process photos in a more automated and bulk manner.



There are no comments on this article.

Back to Articles


© 2008-2017 Greg Cope