gpt4 book ai didi

Java nashorn - 从 JavaScript 获取所有绑定(bind)

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:53:21 25 4
gpt4 key购买 nike

我创建了一些绑定(bind)并将它们传递给引擎和全局范围

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

现在在 js 方面,我想打印特定范围内的所有可用绑定(bind)。

我该怎么做?

最佳答案

您可以将绑定(bind)添加到一个包含对引擎的引用的对象,并创建用于从中解析键列表的方法。像这样:

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[]{});
}
}


}

上面程序的输出是

Engine vars:
info
engineVar
newEngineVar
key

Global vars:
global

关于Java nashorn - 从 JavaScript 获取所有绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38157918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com