Google Web Toolkit (Beta)
Search this site:

# 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 type | How it appears to JavaScript code
--- | ---
a Java numeric primitive | a JavaScript numeric value, as in `var x = 42;`
`String` | a JavaScript string, as in `var s = "my string";`
`boolean` | a 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 type | What must be passed
--- | ---
a Java numeric primitive | a JavaScript numeric value, as in `return 19;`
`String` | a 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

- A Java numeric primitive is one of `byte`, `short`, `char`, `int`, `long`, `float`, or `double`. You must ensure the value is appropriate for the declared type. Returning `3.7` when the declared type is `int` will cause unpredictable behavior.
- Java `null` and JavaScript `null` are identical and always legal values for any non-primitive Java type. JavaScript `undefined` is not identical to `null`; never return `undefined` from a JSNI method or unpredictable behavior will occur.
- Violating any of these marshaling rules in hosted mode will generate a `com.google.gwt.dev.shell.HostedModeException` detailing the problem. This exception is not translatable and never thrown in web mode.
- JavaScriptObject is a magical type that gets special treatment from the GWT compiler and hosted browser. Its purpose is to provide an opaque representation of native JavaScript objects to Java code.

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`.