GWT JSNI - problem passing Strings

2020-02-05 10:07发布

I'm trying to provide some function hooks in my GWT project:

private TextBox hello = new TextBox();
private void helloMethod(String from) { hello.setText(from); }
private native void publish() /*-{
 $wnd.setText = $entry(this.@com.example.my.Class::helloMethod(Ljava/lang/String;));
}-*/;

publish() being called in onModuleLoad(). But this doesn't work, providing no feedback as to why in the dev console. I've also tried:

private native void publish() /*-{
 $wnd.setText = function(from) {
  alert(from);
  this.@com.example.my.Class::helloMethod(Ljava/lang/String;)(from);
 }
}-*/;

which will toss a java.lang.ClassCastException in the FireBug console, though the alert fires just fine. Suggestions?

标签: gwt jsni
2条回答
Evening l夕情丶
2楼-- · 2020-02-05 10:58

helloMethod is an instance method, and as such it requires the this reference to be set, when it is called. Your first example doesn't do this at call time. Your second example attempts to do this, but there's a little mistake, which one can make easily in JavaScript: The this reference in

$wnd.setText = function(from) {
  this.@com.example.my.Class::helloMethod(Ljava/lang/String;)(from);
};

points to the function itself. To avoid this, you'll have to do something like:

var that = this;
$wnd.setText = function(from) {
  that.@com.example.my.Class::helloMethod(Ljava/lang/String;)(from);
};

Or better:

var that = this;
$wnd.setText = $entry(function(from) {
  that.@com.example.my.Class::helloMethod(Ljava/lang/String;)(from)
});
查看更多
看我几分像从前
3楼-- · 2020-02-05 11:03
private native void publish(EntryPoint p) /*-{
 $wnd.setText = function(from) {
  alert(from);
  p.@com.example.my.Class::helloMethod(Ljava/lang/String;)(from);
 }
}-*/;

Could you give this code a try?

查看更多
登录 后发表回答