Graaljs: Access Java Map property-values using JSON / dot-notation

Created on 2 Feb 2019  路  2Comments  路  Source: oracle/graaljs

I'm expecting the last line to work but it does not:

        Context c = Context.newBuilder("js").allowHostAccess(true).build();
        // Context c = Context.newBuilder().option("js.nashorn-compat", "true").build();

        Value bindings = c.getBindings("js");
        Map map = new HashMap();
        map.put("a", 1);
        bindings.putMember("foo", map);

        Value v = c.eval("js", "foo");
        assertEquals(map, v.as(Map.class));

        v = c.eval("js", "foo.get('a')");
        assertEquals(1, v.asInt());

        v = c.eval("js", "foo.a");
        assertEquals(1, v.asInt()); // fails

I have a Nashorn based app that extensively uses expressions like foo.bar.baz to access nested properties on Java maps - and it works great.

Is there any way I can get the same behavior in Graal. I tried various conversions such as Context.asValue(map) but no luck. Any advice would be appreciated !

Most helpful comment

It works when using a ProxyObject for a map:

        Context c = Context.create("js");

        Value bindings = c.getBindings("js");
        Map<String, Object> map = new HashMap<>();
        map.put("a", 1);
        bindings.putMember("foo", ProxyObject.fromMap(map));

        Value v = c.eval("js", "foo.a");
        assertEquals(1, v.asInt()); // success

All 2 comments

It works when using a ProxyObject for a map:

        Context c = Context.create("js");

        Value bindings = c.getBindings("js");
        Map<String, Object> map = new HashMap<>();
        map.put("a", 1);
        bindings.putMember("foo", ProxyObject.fromMap(map));

        Value v = c.eval("js", "foo.a");
        assertEquals(1, v.asInt()); // success

@fdummert thank you very much ! what a relief :) and I see that ProxyArray is the way to go for arrays.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

frank-dspeed picture frank-dspeed  路  3Comments

frieck picture frieck  路  6Comments

pmlopes picture pmlopes  路  3Comments

hashtag-smashtag picture hashtag-smashtag  路  5Comments

h2oche picture h2oche  路  4Comments