JavaScriptDemo.java

Download JavaScriptDemo.java

 1: // JavaScriptDemo - This console app evaluates any valid JavaScript
 2: // expression passed in as command line arguments.  This show how to
 3: // invoke an external (scripting) language; currently, only JavaScript
 4: // is included in the JRE.
 5: //
 6: // Written 10/2012 by Wayne Pollock, Tampa Florida USA, from code
 7: // posted on comp.lang.java.programmer netnews group on 10/15/12, by
 8: // John B. Matthews, in thread "Re: Operation in String to Double conversion".
 9: //
10: // Examples:  java JavaScriptDemo "2 + 3 * Math.pow(4, 2)"
11: //            java JavaScriptDemo "new Date().toUTCString()"
12: //            java JavaScriptDemo "'Hello, ' + 'World!'"
13: 
14: import java.util.*;
15: import javax.script.*;
16: 
17: public class JavaScriptDemo {
18: 
19:   public static void main ( String [] args ) {
20: 
21:     // If no arguments, print brief usage message:
22:     if ( args == null || args.length == 0 ) {
23:       System.out.println( "Usage: java JavaScriptDemo"
24:         + " \"some_JavaScript_expression\"" );
25:       return;
26:     }
27: 
28:     ScriptEngineManager mgr = new ScriptEngineManager();
29: /*
30:     // List all available scripting engines:
31:     List<ScriptEngineFactory> factories = mgr.getEngineFactories();
32:     for ( ScriptEngineFactory sef : factories ) {
33:         System.out.println( sef );
34:     }
35: */
36:     // Select an available JavaScript Engine by extension:
37:     ScriptEngine engine = mgr.getEngineByExtension( "js" );
38: 
39:     // Concatenate command line args into a string, using space as separator:
40:     StringBuilder sb = new StringBuilder();
41:     for ( String s : args ) {
42:        sb.append( s ).append( ' ' );
43:     }
44:     String expression = sb.toString();
45: 
46:     // Evaluate the (hopefully legal) JavaScript expression:
47:     try {
48:         System.out.println( engine.eval( expression ) );
49:     } catch ( ScriptException ex ) {
50:         System.err.println( "Invalid JavaScript expression!" );
51:     }
52:   }
53: }