Java-JavaScript interoperability, promises and exception handling

CheerpJ 1.1 features a new API based on standard promises to call Java methods (converted by CheerpJ) from HTML5/JavaScript.

The standard API available in CheerpJ 1.0 (based on cjCall and cjNew ) is convenient, and is based under the hood on Java reflection to resolve methods. When planning to invoke many Java methods from JavaScript, or when performance is important, this can lead to an unacceptable overhead. This is particularly relevant when using CheerpJ to convert a Java library.

The new APIs available in CheerpJ 1.1 — named cjResolveCall and cjResolveNew — are optimised to rely on reflection only once, and avoid any overhead in further calls to the same method.

This is an example of the new APIs:

cjResolveCall supports both instance and static methods of classes. The third parameter (for both APIs) is an array of Java types and it is only required for overloaded method names.

cjResolveCall and cjResolveNew are asynchronous, like most of CheerpJ's APIs. To get the actual result you can either use .then() or — better — the async / await functionality of JavaScript. For example:

The returned value is an opaque handle to the desired method (or constructor), which can now be called an arbitrary number of times very efficiently.

Alternatively resolvedMethod can also be used directly as a function, for example:

resolvedMethod(arg1, arg2, arg3);

Please note that this convenient form can unfortunately only be used on the main thread, not on Workers. For more information see WebWorker API.

Starting from CheerpJ 1.1, these APIs return standard JavaScript promises. While before only the basic then(...) pattern could be used, now the full suite of Promise capabilities are available including chaining, async / await and exception handling using catch. For example:

The catch callback will receive the error message (i.e. the detail message if the Java Exception). This is also supported when using the WebWorker API to run Java code in a separate worker.