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?



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

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


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);
    // 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) {


Have a look at Rhino:


Oracle Nashorn provides interoperability between the Java and JavaScript worlds. That means your Java code can call JavaScript code, and vice versa. Basic tutorial on understanding how to write program using Oracle Nashorn.


The Rhino JavaScript engine that was included in JDK 6 is being replaced by a new engine called Nashorn for JDK 8.

The Oracle blog for Nashorn contains news as well as source code samples.


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.


I just wanted to answer something new for this question - J2V8.

Author Ian Bull says "Rhino and Nashorn are two common JavaScript runtimes, but these did not meet our requirements in a number of areas:

Neither support ‘Primitives‘. All interactions with these platforms require wrapper classes such as Integer, Double or Boolean. Nashorn is not supported on Android. Rhino compiler optimizations are not supported on Android. Neither engines support remote debugging on Android.""

Highly Efficient Java & JavaScript Integration

Github link


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.