ZehnVon12
ZehnVon12

Reputation: 4176

GWT JsInterop: JsType property with "-" in name

I want to wrap the Javascript object

{"Ctrl-Space": "autocomplete"}

to GWT. When I try:

@JsType
public class ExtraKeyType {
    @JsProperty(name = "Ctrl-Space")
    public String ctrlSpace = "autocomplete";
}

I get the error

String ExtraKeyType.ctrlSpace' has invalid name 'Ctrl-Space

Is it possible to wrap this with JsInterop?

Upvotes: 2

Views: 676

Answers (2)

Robert Newton
Robert Newton

Reputation: 1611

You cannot do this using the simple @JsProperty annotion.

A work-around is to use the jsinterop-base library, classes Js and JsPropertyMap, as follows:

import jsinterop.annotations.JsOverlay;
import jsinterop.base.Js;

@JsType
public class ExtraKeyType {
    //@JsProperty(name = "Ctrl-Space")
    //public String ctrlSpace = "autocomplete";

    @JsOverlay
    public final void setCtrlSpace(String value) {
        Js.asPropertyMap(this).set("Ctrl-Space", value);
    }

    @JsOverlay
    public final String getCtrlSpace() {
        return Js.asPropertyMap(this).getAny("Ctrl-Space").asString();
    }

}

Upvotes: 0

Ignacio Baca
Ignacio Baca

Reputation: 1578

It's not possible, but it's on purpose. It's limited by this regex https://github.com/gwtproject/gwt/blob/master/dev/core/src/com/google/gwt/dev/js/JsUtils.java#L496 which forces valid JS identifiers.

You should note that this is illegal { with-dash: "bad" } because dashes aren't valid for identifiers https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types. But this is legal { with_underscore: "right" } which works correctly in JsInterop. BUT, JS is tricky, and it actually support invalid identifiers, just need to be quoted, so you can write { "with-dash": "right too" }.

So look like what you are asking for is to improve JsInterop to support invalid identifiers in properties of native types. I think this is not already supported because for example invalid identifier cannot be used with the dot notation, so the generated JS code will be different for invalid identifiers. But looks like an interesting (almost required) feature if you want to map JSON to Java types.

This is your next step: https://github.com/gwtproject/gwt/issues/new

Upvotes: 1

Related Questions