Java nashorn - 从JavaScript获取所有绑定

时间:2016-07-02 08:00:21

标签: java nashorn

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

select 
    t.*,
    if(@grp = t.user_id, @rowno := @rowno + 1, @rowno := 1) as rowno,
    @grp := t.user_id
from (
    select  n.user_id,t.name,count(t.name) ct from
    temp_user_batches n inner join tags t on n.id=t.note_id
    where user_id IN (9122,9125,9126,9127) 
    group by n.user_id,t.name
    order by n.user_id, count(t.name) desc
) t
cross join (select @grp := null, @rowno := 0) v
having rowno = 1
order by 1,3 desc

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

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以将绑定添加到保存对引擎的引用的对象,并创建用于从中解析键列表的方法。像这样:

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