简体   繁体   English

JSNI - 从 JS function 调用 Java 方法

[英]JSNI - invoke Java method from JS function

I am trying to invoke a java method right from my JSNI function but for some reason it never works.我正在尝试直接从我的 JSNI function 调用 java 方法,但由于某种原因它永远无法正常工作。 What am I doing wrong here?我在这里做错了什么? :( :(

Here is my code这是我的代码

/**
   For UI button click method...
*/
private native void test(String param)
/*-{

var a=(function b(p)
{
 this.@com.(...).TestClass::setTest(Ljava/lang/String;)(p);

})(param);

}-*/

private void setTest(String param){Window.alert(param);}

All useful comments are appreciated感谢所有有用的评论

You need to take a reference to this outside the function block:您需要在function块之外this进行引用:

/**
 * For UI button click method...
 */
private native void test(String param) /*-{
    var theInstance = this;
    var a = ( function b(p) {
        theInstance.@com.(...).TestClass::setTest(Ljava/lang/String;)(p);
    })(param);
}-*/;

private void setTest(String param){
    Window.alert(param);
}

Your usage of the this keyword may cause the problem.您对 this 关键字的使用可能会导致问题。 In your context the this keywords points to the closure在您的上下文中, this关键字指向闭包

(function b(p)
{
 this.@com.(...).TestClass::setTest(Ljava/lang/String;)(p);

})(param);

Ideally it should point to the function that GWT compiles from理想情况下,它应该指向 GWT 编译的 function

private native void test(String param)

this statement.这个说法。

Try using this code segment (I'm not sure if I got the syntax right, verify with GWT JSNI wiki):尝试使用此代码段(我不确定我的语法是否正确,请使用 GWT JSNI wiki 进行验证):

private native void test(String param)
/*-{    
var a = this.@com.(...).TestClass::setTest(Ljava/lang/String;)(param);    
}-*/

BTW, Having a function whose sole purpose is to call another function is a code smell.顺便说一句,拥有一个 function 其唯一目的是调用另一个 function 是代码异味。

Yes, as Zasz is pointing out, you are overcomplicating your code (expect if you really want to provide a JavaScript method, but in that case you have to do it in a complete different way...)是的,正如 Zasz 指出的那样,您的代码过于复杂(如果您真的想提供 JavaScript 方法,但在这种情况下,您必须以完全不同的方式进行操作......)

So I tested the code and this works:所以我测试了代码,这有效:

/*    JNI Example method... */
private native void test(String param) /*-{  
    this.@com.stefank.client._53_JavaScriptOverlayTypes::setTest(Ljava/lang/String;)(param); 
}-*/;

private void setTest(String param){
    Window.alert(param);
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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