简体   繁体   English

如何从GWT JSNI访问静态方法ID

[英]How to access static method id from GWT JSNI

I fail to get the request_id from MyJavaObject in GWT JSNI like this example but got undefined value. 我无法从GWT JSNI中的MyJavaObject中获得request_id,例如本示例,但是得到了未定义的值。

Please help. 请帮忙。

JAVA CLASS JAVA类

package com.my.app;

    class MyJavaObject
    {
        public final int request_id;

        public MyJavaObject(int request_id)
        {
            this.request_id = request_id;
        }

        public static final MyJavaObject MY_REQUEST = new MyJavaObject(13);
    }

GWT JSNI GWT JSNI

public static native void expose()/*-{

    var val = @com.my.app.MyJavaObject::MY_REQUEST.request_id;

}-*/;

You're trying to access a non-static member variable from a static method without any reference to this object 您正在尝试从静态方法访问非静态成员变量,而无需对该对象进行任何引用

Read the doc here: http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html#methods-fields , your method should be written like that: 在此处阅读文档: http : //www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html#methods-fields ,您的方法应这样编写:

public static native void expose()/*-{

    var val = this.@com.my.app.MyJavaObject::request_id;
    // Do something with val...
}-*/;

Edit after comment: 评论后编辑:

Maybe this could work: 也许这可以工作:

public static native void expose()/*-{

    var val = @com.my.app.MyJavaObject::MY_REQUEST.@com.my.app.MyJavaObject::request_id;
    // Do something with val...
}-*/;

if it does not, pass your object as a parameter: 如果没有,则将您的对象作为参数传递:

public static native void expose( MyJavaObject obj)/*-{

    var val = obj.@com.my.app.MyJavaObject::request_id;
    // Do something with val...
}-*/;

and either call expose( MY_REQUEST ) directly or create a helper function 然后直接调用expose( MY_REQUEST )或创建一个辅助函数

public static native void expose() {
    return expose( MY_REQUEST );
}

The problem is that while you are referencing the full type where the MY_REQUEST field lives, you are not referencing the full type where the request_id lives. 问题在于,当您引用MY_REQUEST字段所在的完整类型时,却没有引用request_id所在的完整类型。 Since JS has a very different concept of type hierarchy, when we reference Java from JS, we need to be very specific. 由于JS具有不同的类型层次结构概念,因此当我们从JS引用Java时,我们需要非常具体。

When you referenced MY_REQUEST , you did so by using the @classname::fieldname syntax. 引用MY_REQUEST ,是通过使用MY_REQUEST :: fieldname语法来实现的。 You must also do this to get the request_id field: 您还必须执行此操作以获取request_id字段:

public static native void expose()/*-{
  var myRequest = @com.my.app.MyJavaObject::MY_REQUEST;
  var id = myRequest.@com.my.app.MyJavaObject::request_id;
  //do something useful with these values...
}-*/;

This could also be achieved in one line, but tends to be unreadable, so I'd avoid it. 这也可以一行完成,但往往难以理解,因此我避免使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM