简体   繁体   中英

Accessing NativeSet members in Mozilla Rhino from Java

I need to iterate over members of a NativeSet evaluated by Mozilla Rhino. My current need a meaningful toString method, but a more general approach would probably be useful for more people.

Here's the code:

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();
}

Current (highly inefficient) workaround: extract the set to a new mini-program, convert to an array, get the items from the array. Any better solutions are welcome.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM