Google Web Toolkit (Beta)
Search this site:

# Accessing Java Methods and Fields from JavaScript

It can be very useful to manipulate Java objects from within the JavaScript implementation of a JSNI method. There is a special syntax for this.

## Invoking Java methods from JavaScript

Calling Java methods from JavaScript is somewhat similar to calling Java methods from C code in JNI. In particular, JSNI borrows the JNI mangled method signature approach to distinguish among overloaded methods.

JavaScript calls into Java methods are of the form

    [instance-expr.]@class-name::method-name(param-signature)(arguments)

where

[instance-expr.]
  must be present when calling an instance method and must be absent when calling a static method
class-name
  is the fully-qualified name of the class in which the method is declared (or a subclass thereof)
param-signature
  is the internal Java method signature as specified here but without the trailing signature of the method return type since it isn't needed to choose the overload
arguments
  the actual argument list to pass to the called method

## Accessing Java fields from JavaScript

Static and instance fields can be accessed from handwritten JavaScript. Field references are of the form

    [instance-expr.]@class-name::field-name

## Example

    public class JSNIExample {

      String myInstanceField;
      static int myStaticField;

      void instanceFoo(String s) {
        // use s
      }

      static void staticFoo(String s) {
        // use s
      }

      public native void bar(JSNIExample x, String s) /*-{
        // Call instance method instanceFoo() on this
        this.@com.google.gwt.examples.JSNIExample::instanceFoo(Ljava/lang/String;)(s);

        // Call instance method instanceFoo() on x
        x.@com.google.gwt.examples.JSNIExample::instanceFoo(Ljava/lang/String;)(s);

        // Call static method staticFoo()
        @com.google.gwt.examples.JSNIExample::staticFoo(Ljava/lang/String;)(s);

        // Read instance field on this
        var val = this.@com.google.gwt.examples.JSNIExample::myInstanceField;

        // Write instance field on x
        x.@com.google.gwt.examples.JSNIExample::myInstanceField = val + " and stuff";

        // Read static field (no qualifier)
        @com.google.gwt.examples.JSNIExample::myStaticField = val + " and stuff";
      }-*/;

    }

Tip
When writing JSNI code, it's helpful to occasionally run in web mode. The JavaScript compiler checks your JSNI code and can flag errors at compile time that you wouldn't catch until runtime in hosted mode.