How can I use JavaScript in Java? [closed]
I wanted to build a small product in which I wanted to give a kind of feature in which user can write a script language kind of JavaScript.
And also from JavaScript able to build objects and calling methods on them.
Is there any framework for this?
Solution 1:
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.
Solution 2:
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.
}
}
Solution 3:
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());
}
}
}