GWT - Calling instance method from external javascript
Asked Answered
G

1

8

There is this $entry method that we can use in GWT to allow external javascript to execute java methods. You can see the explanations in their documentation https://developers.google.com/web-toolkit/doc/latest/DevGuideCodingBasicsJSNI?hl=fr#calling

However, the example there is only with static methods. I'm trying to write it for a non-static method and when I try to call it, I get an exception :

java.lang.ClassCastException: Cannot cast com.google.gwt.core.client.JavaScriptObject$ to mypackage.MyModule

Here is my code :

public native void setRefreshModuleCallback() /*-{
    $wnd.refreshModule = $entry(function() {
        [email protected]::refreshModuleJava();
        alert('test');
    });
}-*/;

public void refreshModuleJava() {
    logger.log(Level.WARNING, "REFRESH");
}

What I find very funny is that alert is called, I see the result in the browser, but the call just before is not performed.

Do you know if it's actually possible to do such thing ?

Gottwald answered 7/3, 2013 at 15:29 Comment(1)
Note that I had a look at this post and it didn't help (or I missed something) #9677460Gottwald
D
11

$entry is not about calling java, it's about ensuring a few things go well in GWT: exceptions are routed to the GWT.UncaughtExceptionHandler, and commands scheduled via Scheduler#scheduleEntry and Scheduler#scheduleFinally are correctly called.

Your problem is the this. When the function is called, this is not your MyModule class (it's most probably the $wnd object). This is why the question you linked to uses var that = this. It's about scoping.

You also need to actually call the method, not only reference it: in JSNI, the first pair of parens are for the formal parameters (to disambiguate overloads), and you need another pair passing the actual arguments: [email protected]::refreshModuleJava()().

Demoralize answered 7/3, 2013 at 15:37 Comment(3)
I tried with 'var that = this;' and calling '[email protected]::refreshModuleJava();' and still get the same behaviorGottwald
Updated answer with additional info, but that var that = this should have at least make the error disappear.Demoralize
@ThomasBroyer Exhaustive explanation. You saved my day.Ridglee

© 2022 - 2024 — McMap. All rights reserved.