Wednesday, September 18, 2019

Jsinterop: java arrays, native arrays, JsArray and strings

Hi,

I want to know if a java array is the same underlying object with a js native array.

    @JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object")
    public static class MyObject {
        int x;
       
        @JsOverlay
        public static MyObject create(int x) {
            final MyObject o = new MyObject();
            o.x = x;
            return o;
        }
    }


    @Override
    public void onModuleLoad() {
        // check if java arrays are implemented by the same underlying native array
        final MyObject[] java_array = new MyObject[] { MyObject.create(1), MyObject.create(4), MyObject.create(16) };
        DomGlobal.console.log((Object) java_array);
        // cast to nativeJsArray<double>
        final JsArray<MyObject> js_array = Js.uncheckedCast(java_array);
        DomGlobal.console.log(js_array);
        // delete second object
        // DomGlobal.window.alert("Check this out");
        js_array.splice(1, 1);
        DomGlobal.console.log((Object) java_array);
        DomGlobal.console.log(js_array);
        return;
   }

Results:

Array(3) [ {}, {}, {} ]
Array(3) [ {}, {}, {} ]
Array [ {}, {} ]
Array [ {}, {} ]

So the splice call succeeds and I can remove elements from the java array. Cool. So this is evidence that java arrays are backed by js arrays,

So
  • Arrays, double are mapped to native types.
  • We have @JsFunction and Function
  • int is mapped to js number --> double
Is it possible to also map java.lang.String to native JsString

        final JsString x1 = new JsString("x1");
        DomGlobal.console.log(x1);
        final String x2 = Js.uncheckedCast(x1);
        DomGlobal.console.log((Object) new String[] {x2});
        final String x3 = x2.replaceAll("1", "3");
        DomGlobal.console.log((Object) new String[] {x3});
        return;

Results:
String { "x1" } <- native js string
Array [ String ] <-- java clas String with value "x1"
Array [ "x3" ] <- native js string ???? Why?

I don't really understand the results. Any comment?



--
Vassilis Virvilis

--
You received this message because you are subscribed to the Google Groups "GWT Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-web-toolkit+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-web-toolkit/CAKbOjEyLT3BTSoCDM-2SkmGz1BD93ynCDw9GvgG5B4p8ovUp0g%40mail.gmail.com.

No comments:

Post a Comment