Search code examples
javascriptjavagraalvmgraaljs

Access complex Javascript object in Java GraalVM


I have a use case where I have a java Map which I convert into ProxyMap, use that map in javascript using context.eval and then create a new object in js (nested json). Now I want to use the object that was created in javascript back in java preferably a Map.

Now my js created object is dynamic and I do not know what all fields might be present.

So basically what I am doing is:

  1. context.getBindings("js").putMember("input", ProxyObject.fromMap(map));
  2. Value js = context.eval("js", "var obj = {'a':input['type']};");
  3. Now I need to get this obj as a Map in Java.

From what I have found out is that I can access the fields of obj in java using getMember but as obj can be dynamic and can be quite complex as well, I was hoping that there might be another way out?


Solution

  • You can convert to a Map using the Value.as(Map.class) method.

    Something like:

     assert context.eval("js", "({foo:'bar'})").as(Map.class).get("foo").equals("bar");