Sharing objects between Java source and JavaScript

Parameters and return types in JSNI methods are declared as Java types. There are very specific rules for how values passing in and out of JavaScript code must be treated. These rules must be followed whether the values enter and leave through normal method call semantics, or through the special syntax.

Passing Java values into JavaScript

Incoming Java typeHow it appears to JavaScript code
a Java numeric primitivea JavaScript numeric value, as in var x = 42;
String a JavaScript string, as in var s = "my string";
booleana JavaScript boolean value, as in var b = true;
JavaScriptObject (see notes)a JavaScriptObject that must have originated from JavaScript code, typically as the return value of some other JSNI method
Java array an opaque value that can only be passed back into Java code
any other Java Object an opaque value accessible through special syntax

Passing JavaScript values into Java code

Outgoing Java typeWhat must be passed
a Java numeric primitivea JavaScript numeric value, as in return 19;
Stringa JavaScript string, as in return "boo";
boolean a JavaScript boolean value, as in return false;
JavaScriptObject (see notes) a native JavaScript object, as in return document.createElement("div")
any other Java Object (including arrays)a Java Object of the correct type that must have originated in Java code; Java objects cannot be constructed from "thin air" in JavaScript

Important Notes

Tip
When returning a possibly undefined value from a JSNI method, we suggest using the idiom
return (value == null) ? null : value;
to avoid returning undefined.