Calling native V8 JavaScript functions from Java

August 24, 2015 | 1 min Read

J2V8 is a set of Java bindings for V8. J2V8 brings the V8 API to Java developers. We developed J2V8 to help with the performance of Tabris.js, our cross-platform, mobile development toolkit.

A common J2V8 question is, how can I call native JavaScript functions from Java? For example, how can you invoke JSON.stringify() on a V8Object from Java. It turns out to be relatively straightforward.

In the case of JSON, you can acquire this object like any other V8Object. Calling V8Object json = v8.getObject(“JSON”); will return a handle to the native JSON object. From here, you can invoke any function on this object using the executeFunction method from Java. The executeFunction takes the name of the JSFunction you wish to invoke and the list of parameters as a V8Array. Putting this all together, you can serialize any V8Object as a JSON string:

  V8Object v8Object = new V8Object(v8).add("foo", "bar");
  V8Object json = v8.getObject("JSON");

  V8Array args = new V8Array(v8).push(v8Object);
  String result = (String) json.executeFunction("stringify", args);


For more J2V8 tips and tricks, follow me on twitter.

Ian Bull

Ian Bull

Ian is an Eclipse committer and EclipseSource Distinguished Engineer with a passion for developer productivity.

He leads the J2V8 project and has served on several …