Quantcast
Channel: 質問!ITmedia 新着質問(Java/253)
Viewing all articles
Browse latest Browse all 2439

JavaのScriptEngineについて質問です

$
0
0
JavaのScriptEngineに関する質問です. 私が実現したいのは,複数のScriptEngineを独立して動かしたいということなのですが, どうしてもうまく行かずに困っています. 言葉で説明するのは難しいので,サンプルコードを作りました.以下に記載いたします. サンプルを動かすと,scriptEngineとscriptEngine2でスコープを分けているにも関わらず, 相互に変数やメソッドが共有されてしまっています. おそらくは私のScriptEngineの使い方が正しくないのではないかと思うのですが, これを独立して動作させるにはどのようにすればよいか分からず,お知恵を拝借したく存じます. mport javax.script.Bindings; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.SimpleScriptContext; /** ScriptEngineのスコープに関するテストプログラム */ public class TestScope { public static void main(String[] argv){ // 1つ目のエンジンを作成し,スクリプトを実行してみる ScriptEngineManager man=new ScriptEngineManager(); ScriptEngine scriptEngine=man.getEngineByName("jruby"); ScriptContext thisContext = scriptEngine.getContext(); Bindings engineScope = thisContext.getBindings(ScriptContext.ENGINE_SCOPE); String script= "CONSTANT=1 \n" + //定数に1を設定 "def get_constant \n" + " print 'in 1st engine, constant value is ',CONSTANT,'\n' \n"+ " return CONSTANT \n"+ "end\n"; try{ scriptEngine.eval(script, engineScope); scriptEngine.eval("get_constant", engineScope); // "in 1st engine, constant value is 1"と表示される(これは期待どおり) }catch(Exception e){ e.printStackTrace(); } // 2つ目のエンジンは1つ目のエンジンと独立していてほしいので,全オブジェクトを新規にnewする ScriptEngineManager man2=new ScriptEngineManager(); ScriptEngine scriptEngine2=man2.getEngineByName("jruby"); ScriptContext thisContext2 = scriptEngine2.getContext(); Bindings engineScope2 = thisContext2.getBindings(ScriptContext.ENGINE_SCOPE); String script2= "CONSTANT=2 \n" + //定数に2を設定 "def get_constant2 \n" + " print 'in 2nd engine, constant value is ',CONSTANT,'\n' \n"+ " return CONSTANT \n"+ "end\n"; try{ scriptEngine2.eval(script2, engineScope2); // "

Viewing all articles
Browse latest Browse all 2439

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>