tags:

views:

762

answers:

3

I need to call an instance Java method from handwritten Javascript. In the GWT docs it is explained how to do this with static methods and classes and it works fine:

http://code.google.com/p/google-web-toolkit-doc-1-6/wiki/DevGuideJavaFromJavaScript (Calling a Java Method from Handwritten JavaScript)

public MyUtilityClass
{
    public static int computeLoanInterest(int amt, float interestRate, 
                                          int term) { ... }
    public static native void exportStaticMethod() /*-{
       $wnd.computeLoanInterest =
          @mypackage.MyUtilityClass::computeLoanInterest(IFI);
    }-*/;
}

Is it possible to do this? I tried several different combinations, declaring the native methods and using this.@ and instance.@ with no success.

Thanks

A: 

Could you post the the code that is not working? :)

But the way I see it, this.@ will not work, because you don't have an object of that class (in the handwritten JS, that is) and it would be the same as if you called an instance method of a class without creating an object of that class first.

instance.@ should work, but you have to make sure that the instance points to a valid instance of the class at the time of the function call from the handwritten JS.

Igor Klimer
+2  A: 

Hi,

Sure it is possible to do this but you syntax is wrong. I'm typing this without compiling, so I might have some typo's. But this is how I do it. The reason why your approach does not work is that the this variable is not what you would expect.

public MyUtilityClass{    
  public static int computeLoanInterest(int amt, float interestRate, int term)  { ... }    

  public static native void exportStaticMethod() /*-{       
      var _this = this;
      $wnd.computeLoanInterest = function(amt,interestRate,term) {
          [email protected]::computeLoanInterest(IFI)(amt,interestRate,term);    
      };
  }-*/;
}
David Nouls
Note that there is also a project called GwtExporter that can remove the needed for handwriting the JSNI calls. I haven't used it yet but the idea is very interesting.
David Nouls
A: 

David Nouls' answer works, with one correction:
remove the static keyword from the method declarations.

Tomer