我正在尝试在我的 GWT 项目中提供一些函数 Hook :
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()
被叫到 onModuleLoad()
.但这不起作用,在开发控制台中没有提供有关原因的反馈。我也试过:private native void publish() /*-{
$wnd.setText = function(from) {
alert(from);
this.@com.example.my.Class::helloMethod(Ljava/lang/String;)(from);
}
}-*/;
这将抛出
java.lang.ClassCastException
在 FireBug 控制台中,虽然 alert
火就好了。建议?
最佳答案
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)
});
关于GWT JSNI - 传递字符串的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5234735/