Java Interoperability

GraalVM includes a JavaScript language execution runtime and allows interoperability with Java code. This document describes the features and usage of this JavaScript-to-Java interoperability feature.

For a reference of GraalVM public API, see JavaScript Compatibility. Migration guides for Rhino and Nashorn are also available.

By default, GraalVM ships with js and node native launchers. Although other builds are possible, the following examples assume this setup is used.

Enabling Java Interoperability

In GraalVM, the js and node launchers are started in an ahead-of-time compiled native mode by default. In that mode, Java interoperability is not available.

To enable Java interoperability, the --jvm option has to be provided to the native launcher. This way, GraalVM JavaScript is executed on a traditional JVM and allows full Java interoperability.


In order to load Java classes you need to have them on the Java classpath. You can specify the classpath with the --vm.classpath=<classpath> option (or short: --vm.cp=<classpath>):

node --jvm --vm.cp=/my/class/path
js --jvm --vm.cp=/my/class/path

The method Java.addToClasspath() can be used to programmatically add to the classpath at runtime.

Polyglot Context

The preferred method of launching GraalVM JavaScript with Java interop support is via polyglot Context. For that, a new org.graalvm.polyglot.Context is built with the hostAccess option allowing access and a hostClassLookup predicate defining the Java classes you allow access to:

Context context = Context.newBuilder("js")
    //allows access to all Java classes
    .allowHostClassLookup(className -> true)
context.eval("js", jsSourceCode);

See the Polyglot Programming reference for more details.

ScriptEngine (JSR 223)

The org.graalvm.polyglot.Context is the preferred execution method for interoperability with GraalVM’s languages and tools. In addition, JavaScript running on GraalVM is fully compatible with JSR 223 and supports the ScriptEngine API. Internally, the GraalVM’s JavaScript ScriptEngine wraps a polyglot context instance:

ScriptEngine eng = new ScriptEngineManager()
Object fn = eng.eval("(function() { return this; })");
Invocable inv = (Invocable) eng;
Object result = inv.invokeMethod(fn, "call", fn);

Access Java from JavaScript

GraalVM provides a set of features to allow interoperability from JavaScript to Java. While Rhino, Nashorn, and GraalVM JavaScript have a mostly comparable overall feature set, they differ in exact syntax, and, partly, semantics.

Class Access

To access a Java class, GraalVM JavaScript supports the Java.type(typeName) function:

var FileClass = Java.type('');

By default, Java classes are not automatically mapped to global variables, e.g., there is no java global property in GraalVM JavaScript. Existing code accessing, e.g.,, should be rewritten to use the Java.type(name) function:

//GraalVM JavaScript compliant syntax
var FileClass = Java.type("");
//backwards-compatible syntax
var FileClass =;

GraalVM JavaScript provides Packages, java, and similar global properties for compatibility. However, explicitly accessing the required class with Java.type is preferred whenever possible for two reasons:

  1. It allows resolving the class in one step rather than trying to resolve each property as a class.
  2. Java.type immediately throws a TypeError if the class cannot be found or is not accessible, rather than silently treating an unresolved name as a package.

The flag can be used to deactivate the global fields of Java packages (set false to avoid creation of the fields; default is true).

Constructing Java Objects

Java objects can be constructed with JavaScript’s new keyword:

var FileClass = Java.type('');
var file = new FileClass("");

Field and Method Access

Static fields of a Java class, or fields of a Java object, can be accessed like JavaScript properties:

var JavaPI = Java.type('java.lang.Math').PI;

Java methods can be called like JavaScript functions:

var file = new (Java.type(''))("");
var fileName = file.getName();

Conversion of Method Arguments

JavaScript is defined to operate on the double number type. GraalVM JavaScript might internally use additional Java data types for performance reasons (e.g., the int type).

When calling Java methods, a value conversion might be required. This happens when the Java method expects a long parameter, and an int is provided from GraalVM JavaScript (type widening). If this conversion causes a lossy conversion, a TypeError is thrown:

void longArg   (long arg1);
void doubleArg (double arg2);
void intArg    (int arg3);
javaObject.longArg(1);     //widening, OK
javaObject.doubleArg(1);   //widening, OK
javaObject.intArg(1);      //match, OK

javaObject.longArg(1.1);   //lossy conversion, TypeError!
javaObject.doubleArg(1.1); //match, OK
javaObject.intArg(1.1);    //lossy conversion, TypeError!

Selection of Method

Java allows overloading of methods by argument types. When calling from JavaScript to Java, the method with the narrowest available type that the actual argument can be converted to without loss is selected:

void foo(int arg);
void foo(short arg);
void foo(double arg);
void foo(long arg);
//JavaScript;              //will call foo(short arg);,16)); //will call foo(int arg);;            //will call foo(double arg);,32)); //will call foo(long arg);

Note that currently there is no way of overriding this behavior from GraalVM JavaScript. In the example above, one might want to always call foo(int arg), even when foo(short arg) can be reached with lossless conversion (foo(1)). Future versions of GraalVM JavaScript might lift that restriction by providing an explicit way to select the method to be called.

Package Access

GraalVM JavaScript provides a Packages global property:


Array Access

GraalVM JavaScript supports the creation of Java arrays from JavaScript code. Both the patterns suggested by Rhino and Nashorn are supported:

//Rhino pattern
var JArray = Java.type('java.lang.reflect.Array');
var JString = Java.type('java.lang.String');
var sarr = JArray.newInstance(JString, 5);

//Nashorn pattern
var IntArray = Java.type("int[]");
var iarr = new IntArray(5);

The arrays created are Java types, but can be used in JavaScript code:

iarr[0] = iarr[iarr.length] * 2;

Map Access

In GraalVM JavaScript you can create and access Java Maps, e.g., java.util.HashMap:

var HashMap = Java.type('java.util.HashMap');
var map = new HashMap();
map.put(1, "a");

GraalVM JavaScript supports iterating over such maps similar to Nashorn:

for (var key in map) {

List Access

In GraalVM JavaScript you can create and access Java Lists, e.g., java.util.ArrayList:

var ArrayList = Java.type('java.util.ArrayList');
var list = new ArrayList();

for (var idx in list) {

String Access

GraalVM JavaScript can create Java strings with Java interoperability. The length of the string can be queried with the length property (note that length is a value property and cannot be called as a function):

var javaString = new (Java.type('java.lang.String'))("Java");
javaString.length === 4;

Note that GraalVM JavaScript uses Java strings internally to represent JavaScript strings, so the above code and the JavaScript string literal "Java" are actually not distinguishable.

Iterating Properties

Properties (fields and methods) of Java classes and Java objects can be iterated with a JavaScript loop:

var m = Java.type('java.lang.Math')
for (var i in m) { print(i); }
> E
> PI
> abs
> sin
> ...

Access to JavaScript Objects from Java

JavaScript objects are exposed to Java code as instances of This class implements Java’s Map interface.


The JavaImporter feature is available only in Nashorn compatibility mode (js.nashorn-compat option).

Console Output of Java Classes and Java Objects

GraalVM JavaScript provides both print and console.log.

GraalVM JavaScript provides a print built-in function compatible with Nashorn.

The console.log is provided by Node.js directly. It does not provide special treatment of interop objects. Note that the default implementation of console.log on GraalVM JavaScript is just an alias for print, and Node’s implementation is only available when running on Node.js.


Exceptions thrown in Java code can be caught in JavaScript code. They are represented as Java objects:

try {
} catch (e) {


GraalVM JavaScript provides support for interoperability between JavaScript Promise objects and Java. Java objects can be exposed to JavaScript code as thenable objects, allowing JavaScript code to await Java objects. Moreover, JavaScript Promise objects are regular JavaScript objects, and can be accessed from Java using the mechanisms described in this document. This allows Java code to be called back from JavaScript when a JavaScript promise is resolved or rejected.

Creating JavaScript Promise Objects That Can Be Resolved from Java

JavaScript applications can create Promise objects delegating to Java the resolution of the Promise instance. This can be achieved from JavaScript by using a Java object as the “executor” function of the JavaScript Promise. For example, Java objects implementing the following functional interface can be used to create new Promise objects:

public interface PromiseExecutor {
    void onPromiseCreation(Value onResolve, Value onReject);

Any Java object implementing PromiseExecutor can be used to create a JavaScript Promise:

// `javaExecutable` is a Java object implementing the `PromiseExecutor` interface
var myPromise = new Promise(javaExecutable).then(...);

JavaScript Promise objects can be created not only using functional interfaces, but also using any other Java object that can be executed by the GraalVM JavaScript engine (for example, any Java object implementing the Polyglot ProxyExecutable interface). More detailed example usages are available in the GraalVM JavaScript unit tests.

Using await with Java Objects

JavaScript applications can use the await expression with Java objects. This can be useful when Java and JavaScript have to interact with asynchronous events. To expose a Java object to GraalVM JavaScript as a thenable object, the Java object should implement a method called then() having the following signature:

void then(Value onResolve, Value onReject);

When await is used with a Java object implementing then(), the GraalVM JavaScript runtime will treat the object as a JavaScript Promise. The onResolve and onReject arguments are executable Value objects that should be used by the Java code to resume or abort the JavaScript await expression associated with the corresponding Java object. More detailed example usages are available in the GraalVM JavaScript unit tests.

Using JavaScript Promises from Java

Promise objects created in JavaScript can be exposed to Java code like any other JavaScript object. Java code can access such objects like normal Value objects, with the possibility to register new promise resolution functions using the Promise’s default then() and catch() functions. As an example, the following Java code registers a Java callback to be executed when a JavaScript promise resolves:

Value jsPromise = context.eval(ID, "Promise.resolve(42);");
Consumer<Object> javaThen = (value)
    -> System.out.println("Resolved from JavaScript: " + value);
jsPromise.invokeMember("then", javaThen);

More detailed example usages are available in the GraalVM JavaScript unit tests.


GraalVM JavaScript supports multithreading when used in combination with Java. More details about the GraalVM JavaScript multithreading model can be found in the Multithreading documentation.