【问题标题】:How to work with int values in gwt jsni methods如何在 gwt jsni 方法中使用 int 值
【发布时间】:2013-02-17 19:40:59
【问题描述】:

如何在 jsni 方法中使用 int 值?

public class Person extends JavaScriptObject{                                                                                                                     

   // some other methods

   public final native void setPoints(int i)/*-{
       this.points= this.points + i;
   }-*/;

   public final native int getPoints()/*-{
        return this.points;
   }-*/;                                                                                    
}

我在结合 JsArray 的方法中使用它

public static boolean moreThanZeroPoints(JsArray<Person> arr, int index){
     if(arr.get(index).getPoints() > 0){
         return true;
     }
     return false;
}

arr.get(index).getPoints() 中给出以下错误消息:

    uncaught: Exception caught: Exception: caught: something other than an int was returned from JSNI method.
    package-path:: getPoints(): JS value of type undefined, expected int

对于arr.get(index).setPoints(1),我收到相同的错误消息。 怎么了? 请帮忙。

【问题讨论】:

  • 包含这些方法的类是什么? (我想是JavaScriptObject 子类?)“不起作用”是什么意思? (即调用这些方法的代码是什么样的?预期结果是什么?实际结果是什么?)
  • 请添加该类的一些代码。只看到这个sn-p很难帮你。
  • 我编辑了我的问题。希望对您有所帮助。
  • 据我所知,您拥有arr.get(index)... 而没有检查arr 是否在该索引上具有值,这可能导致某种OutOfBoundsException。我将您的setPoints 方法的返回类型更正为void,因为我认为这只是一个错误。如果您直接从代码中复制了它,请修改它。

标签: gwt


【解决方案1】:

因为points 可能不存在,您必须将undefined 强制转换为getPoints() 中的某个整数值;要么添加 hasPoints() 方法,并且仅在定义 points 时调用 getPoints()

// coerce undefined (or null, or 0) to 0
public final native int getPoints() /*-{
  return this.points || 0;
}-*/;

// coerce undefined or null to -1
public final native int getPoints() /*-{
  return (this.points != null) ? this.points : -1;
}-*/;

对于setPoints(),您已经声明了int 的返回类型,但实际上从未returned 任何内容,这相当于在JS 中返回undefined。 qben 编辑了您的答案并通过将返回类型更改为 void 来修复它。

【讨论】:

    【解决方案2】:

    请注意,代码没有引用JavaScript window object directly inside the method。访问浏览器的window and document objects from JSNI时,必须分别引用为$wnd and $doc。您编译的脚本在嵌套框架中运行,并且 $wnd 和 $doc 会自动初始化以正确引用 host page's window and document.

    public final native int setPoints(int i)/-{ 
        $wnd.points=  $wnd.points + i;
     }-/;
    

    应该像下面这样:

    public final native int getPoints()/*-{
        return  eval('$wnd.' + points);;
    
    }-*/;
    

    【讨论】:

    • @Baadshah,在这种情况下,Pero 使用 GWT 覆盖类型,它允许在引用底层 JS 对象的本机方法中使用 this 关键字。有关详细信息,请参阅here
    猜你喜欢
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多