Java and Javastript playing together
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.script.*; | |
class Eval { | |
static ScriptEngineManager manager = new ScriptEngineManager(); | |
static ScriptEngine engine= manager.getEngineByName("js"); | |
public static void main(String args[]) { | |
System.out.println(calc(args[0])); | |
} | |
public static String calc(String line) { | |
try { | |
engine.eval("i="+line); // calculate expression | |
return(engine.get("i").toString()); | |
} | |
catch(ScriptException se) {return("ERROR"); } | |
} | |
} |
One of the features that came with Java 6 is this neat trick: You can have a Javascript runtime on your Java program. You feed it with Javascript code and you can get the value of the variables.
It looks great if you need to use some logic already encoded with Javascript and you need to include it in your Java program. No rewriting is needed then.
I've done a sample program to evalaute a simple arithmetic expression as the first command line parameter of this Java program.
Comments