[java] How can I use JavaScript in Java?

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?

This question is related to java javascript apache object

The answer is


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.
  }
}

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


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());
        }
    }
}


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to apache

Enable PHP Apache2 Switch php versions on commandline ubuntu 16.04 Laravel: PDOException: could not find driver How to deploy a React App on Apache web server Apache POI error loading XSSFWorkbook class How to enable directory listing in apache web server Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details How to enable php7 module in apache? java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor