How can I use JavaScript in Java? [closed] How can I use JavaScript in Java? [closed] apache apache

How can I use JavaScript in Java? [closed]


Rhino is what you are looking for.

Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users.

Update:Now Nashorn, which is more performant JavaScript Engine for Java, is available with jdk8.


Java includes a scripting language extension package starting with version 6.

See the Rhino project documentation for embedding a JavaScript interpreter in Java.

[Edit]

Here is a small example of how you can expose Java objects to your interpreted script:

public class JS {  public static void main(String args[]) throws Exception {    ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");    Bindings bindings = js.getBindings(ScriptContext.ENGINE_SCOPE);    bindings.put("stdout", System.out);    js.eval("stdout.println(Math.cos(Math.PI));");    // Prints "-1.0" to the standard output stream.  }}


You can use ScriptEngine, example:

public class Main {    public static void main(String[] args) {        StringBuffer javascript = null;        ScriptEngine runtime = null;        try {            runtime = new ScriptEngineManager().getEngineByName("javascript");            javascript = new StringBuffer();            javascript.append("1 + 1");            double result = (Double) runtime.eval(javascript.toString());            System.out.println("Result: " + result);        } catch (Exception ex) {            System.out.println(ex.getMessage());        }    }}