Call Java method from JSNI

2019-05-06 23:47发布

问题:

I want to call Java method test() from JSNI variable successHandler(). However, I get error

[ERROR] - Line 110: Missing qualifier on instance method 'com.gw.myProject.client.presenter.payments.PaymentProgramPresenter.test'

Original code:

public static native void purchase(String token) /*-{

      var successHandler = function(status){ // Success handler
        return @com.gw.myProject.client.presenter.payments.PaymentProgramPresenter::test()();
      } 
      var failureHandler = function(status){ // Failure handler
        // $wnd.alert('testing');
      }

      $doc.purchaseAction(token, successHandler, failureHandler);
    }-*/;

    public void test() {
        this.onHide();
    }

回答1:

Your test() is not static. Therefore you will need to make it static or specify an instance or make the purchase non-static.

(This error is the GWT version of "Cannot make a static reference to the non-static method methodName() from the type TypeName")

public native void purchase(String token) /*-{

  var instance = this;

  var successHandler = function(status){ // Success handler
    return instance.@com.gw.myProject.client.presenter.payments.PaymentProgramPresenter::test()();
  } 
  var failureHandler = function(status){ // Failure handler
    // $wnd.alert('testing');
  }

  $doc.purchaseAction(token, successHandler, failureHandler);
}-*/;

public void test() {
    this.onHide();
}

You can find a real good tutorial at gwtproject.org

One more tip. If you create javascript Callbacks within the JSNI, wrap them with en $entry()-function:

$doc.purchaseAction(token,$entry( successHandler ), $entry( failureHandler));

This will enable the GWT uncaughtExceptionHandler