且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Javascript JSNI调用Java

更新时间:2023-12-04 14:24:14

那些JSNI引用除了在java文件中的JSNI代码中不起作用。对JSNI中的Java方法和字段的引用实际上并不是有效的JavaScript,而是JSNI语言的一部分,以使这些本机方法能够使用Java和JavaScript。 JSNI字符串 @ com.smartgwt.client.Version :: getVersion()()将被重写为类似于 $ getVersion1()在PRETTY中,或者在OBF模式下只有一两个字符长,所以你不能依赖那个方法名是相同的。



您需要从应用程序内部导出JavaScript函数,以便此外部JavaScript可以调用它。请查看 https://developers.google.com/web-toolkit/doc / latest / DevGuideCodingBasicsJSNI#calling ,以获取关于此的具体细节。



以下示例显示了您的应用程序的外观:

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

确保您在应用程序的某个位置调用此函数来导出函数 - 任何时候调用此函数,你可以从普通的JavaScript中调用 getSmartGwtVersion() - 不需要使用 frames $ c>或 $ entry


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.