简体   繁体   中英

Call Java from Javascript JSNI

I am using SmartGWT and I wish to access com.smartgwt.client.Version from JavaScript. In Firefox's Web Console, I have tried:

frames[0].$entry(Lcom_smartgwt_client_Version::getVersion()));

and

frames[0].$entry(@com.smartgwt.client.Version.getVersion());

and

frames[0].$entry(@com.smartgwt.client.Version::getVersion());

and

frames[0].$entry(@com.smartgwt.client.Version::getVersion()());

But all of them return a syntax error.

SmartGWT is deployed with my WAR and I can see other SmartGWT classes listed when I do just frames[0] .

What is the right syntax to call this static Java method?

Those JSNI references do not work except in JSNI code in your java files. References to Java methods and fields in JSNI are not actually valid JavaScript, but part of the JSNI language to enable those native methods to both use Java and JavaScript. The JSNI string @com.smartgwt.client.Version::getVersion()() will be rewritten as something like $getVersion1() in PRETTY, or something just one or two characters long in OBF mode, so you can't rely on that method name being the same.

Instead, you need to export a JavaScript function from inside your application so that this external JavaScript can invoke it. Check out https://developers.google.com/web-toolkit/doc/latest/DevGuideCodingBasicsJSNI#calling for specific details on this.

Here is an example of how this might look in your application:

public native void exportGetVersion() /*-{
  $wnd.getSmartGwtVersion = $entry(function() {
    return @com.smartgwt.client.Version::getVersion()();
  });
}-*/;

Make sure you call this function in your app somewhere to export the function - any time after that is called, you can invoke getSmartGwtVersion() from your regular JavaScript - no need to use frames or $entry .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM