Search code examples
gwtclasscastexceptionjsni

ClassCastException when calling JSNI method


I have the following GWT code:

package my.package.name;

public class MyImpl {

    public void scan(AsyncCallback<String> callBack) {
        this.callBack = callBack;
        scanJNSI();
    }

    private native void scanJNSI()/*-{
        var instance = this;
        [email protected]::onError(Ljava/lang/String;)("BROWSER");
    }-*/;

    private void onError(String obj) {
        callBack.onFailure(new Exception(obj));
    }
}

When I call:

instance.scan(new AsyncCallback<String>() {
    @Override
    public void onSuccess(String result) {
        Window.alert(result);
    }

    @Override
    public void onFailure(Throwable caught) {
        Window.alert(caught.getMessage());
    }
});

I get a Caused by: java.lang.ClassCastException: null:

Caused by: java.lang.ClassCastException: null
    at java.lang.Class.cast(Class.java:2990)
    at com.google.gwt.dev.shell.JsValueGlue.get(JsValueGlue.java:163)
    at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:57)
    at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
    at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:337)
    at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:218)
    at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNativeVoid(ModuleSpace.java:289)
    at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeVoid(JavaScriptHost.java:107)
    at my.package.name.MyImpl.scanJNSI(MyImpl.java)
    at my.package.name.MyImpl.scan(MyImpl.java:12)

What can possibly be the class that it couldn't cast ?


Solution

  • I found a workaround:

    I replaced :

    [email protected]::onError(Ljava/lang/String;)("BROWSER");
    

    With:

    [email protected]::onError(Lcom/google/gwt/core/client/JavaScriptObject;)({name:"BROWSER"});
    

    And

    private void onError(String obj) {
        callBack.onFailure(new Exception(obj));
    }
    

    With:

    private void onError(JavaScriptObject obj) {
        JSOModel jso = obj.cast();
        callBack.onFailure(new Exception(jso.get("name")));
    }
    

    And it worked..

    I don't know if using the String class is the problem.