Java bridge


Java bridge

Since the XP runtime is built on top of the JVM, JavaScript developers may also directly invoke and use Java-based code.

The __ object

In Enonic XP, there is a standard object named (double underscore), accessible from any serverside JavaScript code, which provides a way to wrap Java objects in a JavaScript object. The object has functions that allow JavaScript to communicate with Java classes. The newBean function will wrap the Java object named in the parameter, for instance:

var bean = __.newBean('');

This line is from the lib-io library, which is a good example of how this is used. In the Java IOHandlerBean class, there are several methods, like the readLines method:

public List<String> readLines( final Object value )
  throws Exception
      final CharSource source = toCharSource( value );
      return source.readLines();

This method is now accessible as a function on the JavaScript bean and may be invoked from JavaScript, like this:

exports.readLines = function (stream) {
  return __.toNativeObject(bean.readLines(stream));

This results in a global JavaScript function readLines. This example also shows the use of the toNativeObject method, which in this case, converts a Java String array to a JSON object.

TODO: Also check out the reference documentation for the __ object.