Search code examples
javajavascriptgwtjsni

How are JSNI methods handled in a pure Java environment?


I use the following GWT JSNI code which should be used in a shared packaged used by the server and the client:

public static native void alert(String msg) /*-{
  $wnd.alert(msg);
}-*/;


public void doSomething() {
   alert("test");
}

What does the compiler do with this code on the Server when it compiles to pure Java? Is there any way to provide the pure Java version of the code an alternative to the JSNI part?


Solution

  • From the JVM's point of view, they're native methods.
    The /*-{ … }-*/ is a GWT-specific syntax, from a Java Compiler point of view it's just a comment.

    So, if called in a JVM, it'll fail with an UnsatisfiedLinkError.

    If you want to provide specific implementations for GWT vs. a JVM, either use GWT.isScript() if the JVM-specific code is translatable to GWT (you could try annotating it with @GwtIncompatible and see if GWT complains), or you can use super source; see “Overriding one package implementation with another” in http://www.gwtproject.org/doc/latest/DevGuideOrganizingProjects.html#DevGuideModuleXml