how to instantiate a java class from within JSNI

2019-08-28 15:24发布

问题:

I'm trying to instantiate a java type inside a JSNI method body, using the JSO's package-private's ::new() method, but all instances are returned as null handles. how come?

Is it possible to instantiate the class using a similar syntax to Java?

Here is the relevant code:

public class OnChangeHandlerJso extends JavaScriptObject {

    protected OnChangeHandlerJso() {};

    public static native JavaScriptObject create() /*-{

        return function(cm, changeInfo) {

            var eventBus = @com.gigaspaces.codemirror_gwt.client.events.EventUtils::CODE_MIRROR_EVENT_BUS;

            var event = @com.gigaspaces.codemirror_gwt.client.events.EditorContentChangeEvent::new()();

            // could something like this work?
            // var event = new @com.gigaspaces.codemirror_gwt.client.events.EditorContentChangeEvent;

            event.@com.gigaspaces.codemirror_gwt.client.events.EditorContentChangeEvent::setCm(Lcom/gigaspaces/codemirror_gwt/client/jsni/CodeMirrorJso;)(cm);
            event.@com.gigaspaces.codemirror_gwt.client.events.EditorContentChangeEvent::setChangeInfo(Lcom/gigaspaces/codemirror_gwt/client/jsni/ChangeInfoJso;)(changeInfo);
            eventBus.@com.google.gwt.event.shared.EventBus::fireEvent(Lcom/google/gwt/event/shared/GwtEvent;)(event);
        };
    }-*/;
}

回答1:

Solved like this:

The overlay type

public class OnChangeHandlerJso extends JavaScriptObject {

    protected OnChangeHandlerJso() {};

    public static native OnChangeHandlerJso create() /*-{
        return function(cm, changeInfo) {
            @com.gigaspaces.codemirror_gwt.client.vo.OnChangeHandler::handle(Lcom/gigaspaces/codemirror_gwt/client/jsni/CodeMirrorJso;Lcom/gigaspaces/codemirror_gwt/client/jsni/ChangeInfoJso;)(cm, changeInfo);
        };
    }-*/;
}

The handler

public class OnChangeHandler implements JsoWrapper<OnChangeHandlerJso> {

    public static void handle(CodeMirrorJso cmJso, ChangeInfoJso changeInfoJso) {
        // ...
        EventUtils.CODE_MIRROR_EVENT_BUS.fireEvent(new EditorContentChangeEvent(cm, changeInfo));
    }
}


标签: gwt jsni