user592704
user592704

Reputation: 3704

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. 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

Upvotes: 0

Views: 3000

Answers (3)

Stefan
Stefan

Reputation: 14863

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...)

So I tested the code and this works:

/*    JNI Example method... */
private native void test(String param) /*-{  
    [email protected]._53_JavaScriptOverlayTypes::setTest(Ljava/lang/String;)(param); 
}-*/;

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

Upvotes: 0

Manuel Darveau
Manuel Darveau

Reputation: 4635

You need to take a reference to this outside the function block:

/**
 * 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);
}

Upvotes: 2

Zasz
Zasz

Reputation: 12538

Your usage of the this keyword may cause the problem. In your context the this keywords points to the closure

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

})(param);

Ideally it should point to the function that GWT compiles from

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) :

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.

Upvotes: 1

Related Questions