How do I call a Java method from Javascript? I tried the following

http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html#calling

But it is not working. I can't put the JS into Java file because the library uses a callback. In my App.html file:

    function pickerCallback(data) {
        var doc = data[google.picker.Response.DOCUMENTS][0];
        var name= doc[google.picker.Document.NAME];
        var fileId = data.docs[0].id;

        // set the path text field
        //[instance-expr.]@class-name::field-name
        //[instance-expr.]@class-name::method-name(param-signature)(arguments)
        // Call static method 
        //@com.onix.sdm.client.SDM_Mailer::setSelectedFolder(Ljava/lang/String;Ljava/lang/String;)(name, fileId);
        $entry(@com.onix.sdm.client.SDM_Mailer::setSelectedFolder(name, fileId));
    }

In SDM_Mailer.java:

private static void setSelectedFolder(String folder, String id) {
    SDM_Mailer myThis = SDM_Mailer.getInstance();
    myThis.textFolder.setText(folder);
    myThis.folderId = id;
}

When I load the app, in gives this error in the browser console:

Uncaught SyntaxError: Unexpected token ILLEGAL

On this line:

      $entry(@com.onix.sdm.client.SDM_Mailer::setSelectedFolder(name, fileId));

I also tried the line immediately before that (commented for now), which also gave the same error.

有帮助吗?

解决方案

I can't put the JS into Java file because the library uses a callback

That's by design - the purpose of this syntax is not to expose methods where they can be called by external JS, but instead to let you call it from within JSNI. This is because the JSNI can be modified to actually call the java method.

If you want to call Java/GWT methods from in plain js, you must expose them for this. You linked http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html#calling, but didn't actually use the important part:

public static native void exportStaticMethod() /*-{
   $wnd.computeLoanInterest =
      $entry(@mypackage.MyUtilityClass::computeLoanInterest(IFI));
}-*/;

This is the important piece - you must expose the function to where the outside JS can call it, but you must do this exposing from within a JSNI func. Note that we are not calling the function here, just referring to it.

其他提示

I think you missed the Type Parameter:

$entry(@com.onix.sdm.SDM_Mailer::setSelectedFolder(Ljava/lang/String;Ljava/lang/String;)(name, fileId));

JSNI is well explained at DevGuideCodingBasicsJSNI

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top