Search code examples
javascriptjavagwtgwt-jsinterop

Failed to export Java class to JavaScript via JsInterop in GWT


I'm following the GWT documentation Coding Basics - JavaScript: JsInterop to export a Java class to JavaScript via annotation @JsMethod. However, the Java class is not transpiled into JavaScript.

Here's my Java class:

package io.mincongh.client;

import jsinterop.annotations.JsMethod;

public class ExportedMethods {

  @JsMethod
  public static String sayHello(String name) {
    return "Hello, " + name;
  }
}

And my project is built in Maven, via GWT Maven plugin 2.8.2:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>gwt-maven-plugin</artifactId>
  <executions>
    <execution>
      <goals>
        <goal>compile</goal>
        <goal>test</goal>
        <goal>generateAsync</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <runTarget>StockMarket.html</runTarget>
    <modules>
      <module>io.mincongh.StockMarket</module>
    </modules>
  </configuration>
</plugin>

When I call the exported method in my browser's console. Then the method is not defined:

io.mincongh.client.ExportedMethods.sayHello('world');

VM59:1 Uncaught ReferenceError: io is not defined at :1:1


Solution

  • From the specification JsInterop v1.0: Nextgen GWT/JavaScript Interoperability, paragraph @JsType:

    Note that exporting of Java Objects to JavaScript to be accessed by their namespace (e.g. this sample) requires --generateJsInteropExports flag.

    So you need to specify this flag in the Maven GWT plugin:

    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>gwt-maven-plugin</artifactId>
      ...
      <configuration>
        <generateJsInteropExports>true</generateJsInteropExports>
      </configuration>
    </plugin>