2016-07-02 7 views
3

habe ich einige Bindungen und übergeben sie an den Motor und globale BereicheJava nashorn - Holen Sie sich alle Bindungen von javascrict

Bindings bindings = new SimpleBindings(); 
bindings.put... 
scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); 
Bindings bindings1 = new SimpleBindings(); 
bindings1.put... 
scriptEngine.setBindings(bindings1, ScriptContext.GLOBAL_SCOPE); 

Jetzt auf der Seite js Ich mag würde alle avalaible Bindungen in einem bestimmten Umfang drucken.

Wie kann ich das tun?

Antwort

1

Sie könnten eine Bindung zu einem Objekt hinzufügen, das einen Verweis auf die Engine enthält, und Methoden zum Analysieren der Schlüsselliste daraus erstellen. Etwas wie folgt aus:

package nashor; 

import java.io.FileNotFoundException; 
import java.io.FileReader; 

import javax.script.*; 

public class NashorMain { 

    public static void main (String[] args) throws ScriptException { 

     ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn");  
     Bindings b = nashorn.createBindings(); 
     b.put("global", "GLOBAL"); 
     nashorn.setBindings(b, ScriptContext.GLOBAL_SCOPE); 

     b = nashorn.createBindings(); 
     b.put("info", new NashorInfo(nashorn)); 
     b.put("engineVar", "engine"); 
     nashorn.setBindings(b, ScriptContext.ENGINE_SCOPE); 

     nashorn.eval("newEngineVar = 'engine'"); 
     nashorn.eval("print('Engine vars:'); for each (var key in info.getEngineScopeKeys()) print (key)"); 
     nashorn.eval("print();print('Global vars:'); for each (var key in info.getGlobalScopeKeys()) print (key)"); 
    } 

    public static class NashorInfo { 

     private ScriptEngine scriptEngine; 

     public NashorInfo (ScriptEngine scriptEngine) { 
      this.scriptEngine = scriptEngine; 
     } 

     public String[] getEngineScopeKeys() { 
      return scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE).keySet().toArray(new String[]{}); 
     } 

     public String[] getGlobalScopeKeys() { 
      return scriptEngine.getBindings(ScriptContext.GLOBAL_SCOPE).keySet().toArray(new String[]{}); 
     } 
    } 


} 

Die Ausgabe des Programms oben ist

Engine vars: 
info 
engineVar 
newEngineVar 
key 

Global vars: 
global 
Verwandte Themen