J2JS
Home > Docs > Java Native Interface

1. The Java Native Interface

It is possible, but not encouraged, to interact with the native JavaScript runtime in both directions.

2. Java to Native JavaScript Interface

It is possible to inline any JavaScript code through the methods of the ScriptHelper class. The code of the alert method for the Window implementation provides a typical example:

    /**
     * A modal alert dialog is presented to the user.
     */
    public void alert(String message) {
        ScriptHelper.put("message", message);
        ScriptHelper.eval("this.nativeWindow.alert(message)");
    }

Extracted from /projects/j2js-Runtime/src/j2js/client/WindowImpl.java

However, the usage of inlined JavaScript code is discouraged.

3. Native JavaScript to Java Interface

This version of J2JS only supports calls to static Java methods from within JavaScript code. The syntax is

    	j2js.invokeStatic(<className>, <methodSignature>, (optional) <parameters>)
    	

For example, you could fetch the current time and compute to square root of 2 with

    	var time = j2js.invokeStatic("java.lang.System", "currentTimeMillis()");
    	var sqrt2 = j2js.invokeStatic("java.lang.Math", "sqrt(double)", [2]);
Last build on Sat Jan 03 11:06:48 CET 2009