【问题标题】:What is a PoliglotMap in GraalVM?GraalVM 中的 PoliglotMap 是什么?
【发布时间】:2021-07-05 17:45:27
【问题描述】:

我正在我的 Java11 项目中使用 org.graalvm.polyglot 脚本引擎来评估 JavaScript。

要评估的脚本返回一个包含两个条目的 JavaScript 数组。

...
var result={};
result.isValid=false;
result.errorMessage = new Array();
result.errorMessage[0]='Somehing go wrong!';
result.errorMessage[1]='Somehingelse go wrong!';
....

在我的 java 代码中,我尝试评估结果对象:

Value resultValue = context.getBindings(languageId).getMember("result");

在我的 Eclipse 调试器中,我可以看到我收到了一个包含预期值的 PolyglotMap:

我可以使用这样的代码遍历该地图以获取值:

...
   try {
            mapResult = resultValue.as(Map.class);
        } catch (ClassCastException | IllegalStateException | PolyglotException e) {
            logger.warning("Unable to convert result object");
            return null;
        }

        Iterator it = mapResult.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            String itemName = pair.getKey().toString();
            Object itemObject = pair.getValue();
...

通过这种方式,我能够提取布尔值“isValid”。但是对于对象“errorMessage”,我很挣扎。

在 Eclipse 调试器中再次检查对象,它看起来像这样:

如果我测试这个对象,它是一个 instanceOf Map。但我无法从该对象中获取任何值。

谁能帮我理解这个对象到底代表什么以及如何提取'Someting go wrong!''Sometingelse go wrong!'这两个值?

当我遍历第二张地图时,它似乎是空的——即使调试器显示了正确的值。

【问题讨论】:

    标签: javascript java graalvm


    【解决方案1】:

    我不是 100% 确定为什么 as(Map.class) 会这样,可能值得在 github 上创建一个问题来解决这个问题:github.com/oracle/graal

    但是,如果您访问值 using the API 而不转换为 Map,它将按您的预期工作:

    var errorMessage = resultValue.getMember("errorMessage");
    errorMessage.hasArrayElements(); // true
    var _0th = errorMessage.getArrayElement(0); 
    var _1th = errorMessage.getArrayElement(1); 
    

    您也可以将 polyglotMap 转换为 Value 然后进行操作:

    val errorMessage = context.asValue(itemObject);
    errorMessage.hasArrayElements(); // true
    errorMessage.getArrayElement(0);
    

    PolyglotMap 当然有getmethod。价值 javadoc 说:

    Map.class is supported if the value has Value.hasHashEntries() hash entries}, members or array elements. The returned map can be safely cast to Map. For value with members the key type is String. For value with array elements the key type is Long.
    

    您可以尝试使用长键获取它们吗? 我可能遗漏了一些明显的东西,所以无论如何最好在 GitHub 上提出问题。

    【讨论】:

    • 谢谢。是的,这是最好的解决方案,不将对象转换为 Map,而是使用 getMemberKeys() 从多语言对象中获取键,使用 getMember(name) 方法获取值并使用 hasArrayElements() 测试数据结构跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多