GWT JSNI-传递字符串时出现问题

GWT JSNI-传递字符串时出现问题,gwt,jsni,Gwt,Jsni,我试图在我的GWT项目中提供一些函数挂钩: 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;)); }-*/;

我试图在我的GWT项目中提供一些函数挂钩:

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;));
}-*/;
正在
onModuleLoad()
中调用
publish()
。但这不起作用,在开发人员控制台中没有提供关于原因的反馈。我也试过:

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

这将在FireBug控制台中抛出一个
java.lang.ClassCastException
,尽管
警报可以正常触发。建议?

helloMethod
是一种实例方法,因此在调用时需要设置
this
引用。您的第一个示例在调用时不会这样做。您的第二个示例尝试这样做,但有一个小错误,在JavaScript中很容易犯:中的
this
引用

$wnd.setText = function(from) {
  this.@com.example.my.Class::helloMethod(Ljava/lang/String;)(from);
};
指向函数本身。要避免这种情况,您必须执行以下操作:

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

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

你能试试这段代码吗?

Chris,谢谢-你的两个更正都很有效。你说第二个更好-你能解释一下原因吗?@Carl:当然,上面说的是关于
$entry
:“这个隐式定义的函数确保Java派生的方法在安装了未捕获异常处理程序的情况下执行,并提供许多其他实用程序服务。$entry函数是可重入安全的,应该在任何可以从非GWT上下文调用GWT派生的JavaScript的地方使用。“顺便说一句,
var=this;
行是一个典型的JavaScript习惯用法(参见示例)。weeell,我希望你能解释一下开发指南中的这句话的含义(我已经读过了).我熟悉
var that=this;
的习惯用法,但使用@ykartal的解决方案可以使
publish
static成为可能-通常是实现泛化/提取/以其他方式重新定位方法的早期步骤。@Carl:我在互联网上读心术很糟糕。我现在有点犹豫是否要解释这个未可知的方法异常处理程序,如果您理解的话……无论如何,这应该是一个单独的问题。很棒的帖子,您知道为什么要使用
$wnd.setText=$entry(即@com.example.my.Class::helloMethod(Ljava/lang/String;);
抛出类强制转换异常(JavaScriptObject到com.example.my.Class)?非常好-我想我更喜欢这种语法,而不是
var=this
语法。我也更喜欢这种语法。我还更喜欢将此类方法指定为
static
,以进一步表明它们不依赖“Java风格”
this
private native void publish(EntryPoint p) /*-{
 $wnd.setText = function(from) {
  alert(from);
  p.@com.example.my.Class::helloMethod(Ljava/lang/String;)(from);
 }
}-*/;