GWT JSNI - 传递字符串的问题

标签 gwt jsni

我正在尝试在我的 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/

相关文章:

gwt - 如何将 GWT Place URL 从默认的 ":"更改为 "/"?

java - 使用 Guava 10 的谓词和函数接口(interface)与 GWT 2.4.0

java - GWT 中的同步 RPC 调用

javascript - 从 JSNI 调用 Java 方法

gwt - 如何获取gwt表中单击的行、列?

javascript - 在 GWT 中按属性获取 DOM 元素?

GWT 从 javascript 调用 java 方法不起作用

java - 将 Long 数组传递给 JSNI 函数

java - 如何在 GWT JSNI 中将 JavaScript 的返回值转换为 Java?

java - GWT - 编译错误 : No source code is available for type