gwt 2.8.0 jsinterop export无法正常工作

时间:2017-02-27 09:30:49

标签: gwt

查看此文档: https://docs.google.com/document/d/10fmlEYIHcyead_4R1S5wKGs1t2I7Fnp_PaNaa7XTEk0/edit

导出java类并在javascript中保留其方法名称应该像注释类一样简单,并且似乎不起作用。

以下是步骤:

  • 在Eclipse中创建一个新的GWT Web应用程序。项目名称=" jsinterop" ,package =" com.example.jsinterop",使用GWT2.8.0并取消选中App Engine并单击“完成”。
  • 创建新班级

    
    
    package com.example.jsinterop.client;
    
    import jsinterop.annotations.*;
    
    @JsType
    public class Foo {
      public int x;
      public int y;
    
      public int sum() {
        return x + y;
      }
    }
    
    
    
  • 将JSNI方法添加到入口点类

    
    
    public static native int callfoo() /*-{
    		var foo = new com.example.jsinterop.client.Foo();
    		foo.x = 1;
    		foo.y = 2;
    
    		return foo.sum();
    
      }-*/;
    
    
    
  • 在入口点调用此方法。

    
    
    callfoo();
    
    
    

  • 运行应用程序会在Chrome中产生类似这样的javascript错误:

    
    
    Uncaught ReferenceError: com is not defined
        at rb_g$ (Jsinterop.java:155)
        at qb_g$.sb_g$ [as onModuleLoad_0_g$] (Jsinterop.java:77)
        at Array.cyc_g$ (com_00046example_00046jsinterop_00046Jsinterop__EntryMethodHolder.java:3)
        at initializeModules_0_g$ (ModuleUtils.java:44)
        at MJ_g$ (Impl.java:239)
        at PJ_g$ (Impl.java:298)
        at Impl.java:77
        at vxc_g$ (ModuleUtils.java:55)
        at StringHashCache.java:23
    
    
    

    如何让这个简单的实现工作?我有什么遗失的吗?

    提前致谢。

    2 个答案:

    答案 0 :(得分:2)

    默认情况下不会导出任何内容,您必须通过将--generateJsInteropExports传递给GWT(编译器或超级模式)来请求它。

    请注意,GWT 2.x的下一个版本允许您将要导出的软件包/类列入白名单,而不是当前的全有或全无。

    答案 1 :(得分:1)

    您可以将@JsType与特定命名空间一起使用,例如:

    @JsType(namespace = JsPackage.GLOBAL)
    class Foo{...}
    

    应该在没有" com.example.jsinterop.client."

    的JS中使用Foo

    同意吗?

    并考虑使用@JsMethod(isNative = true, namespace = JsPackage.GLOBAL)代替JSNI。

    相关问题