从 Java 访问 Mozilla Rhino 中的 NativeSet 成员

问题描述

我需要遍历由 Mozilla Rhino 评估的 NativeSet 的成员。我目前需要一个有意义的 toString 方法,但更通用的方法可能对更多人有用。

代码如下:

try {
 Context curCtx = Context.enter();
 curCtx.setLanguageVersion(Context.VERSION_ES6);
 ImporterTopLevel importer = new ImporterTopLevel(curCtx);
 Scriptable tlScope = curCtx.initStandardobjects(importer);
 Object resultObj = curCtx.evaluateString( tlScope,"var a=new Set(); a.add(1); a.add(2); a","",1,null);            
  NativeSet ns = (NativeSet)resultObj;
   // >>> How to iterate over ns' members? <<<
 } finally {
  Context.exit();
}

解决方法

当前(非常低效)的解决方法:将集合提取到新的小程序中,转换为数组,从数组中获取项目。欢迎任何更好的解决方案。

private static String toString(NativeSet ns) {
        
    String code = "const arr=[]; ns.forEach(e=>arr.push(e)); arr";
        
     try {
        Context curCtx = Context.enter();
        curCtx.setLanguageVersion(Context.VERSION_ES6);
        ImporterTopLevel importer = new ImporterTopLevel(curCtx);
        Scriptable tlScope = curCtx.initStandardObjects(importer);
        tlScope.put("ns",tlScope,ns);
        Object resultObj = curCtx.evaluateString(
            tlScope,code,"",1,null);
            
        NativeArray arr = (NativeArray) resultObj;
        return arr.getIndexIds().stream().map( id -> stringify(arr.get(id)) ).collect(joining(","));
    } finally {
        Context.exit();
    }
}