Created
August 15, 2014 04:45
-
-
Save hkondo/74bf414e68c23461128e to your computer and use it in GitHub Desktop.
JavaScript in Java, multiple sessions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import javax.script.*; | |
| public class Script | |
| { | |
| public static void main(String args[]) | |
| { | |
| ScriptEngineManager m = new ScriptEngineManager(); | |
| Session s1 = new Session(m); | |
| Session s2 = new Session(m); | |
| try{ | |
| s1.eval("x = 10;"); | |
| s2.eval("x = 20;"); | |
| s1.eval("print('This is s1. The following line should be 10.');"); | |
| s1.eval("print(x);"); | |
| s2.eval("print('This is s2. The following line should be 20.');"); | |
| s2.eval("print(x);"); | |
| s1.eval("print('This is s1. The following line should be 10.');"); | |
| s1.eval("print(x);"); | |
| }catch(ScriptException se){ | |
| System.out.println(se); | |
| }finally{ | |
| } | |
| } | |
| } | |
| class Session | |
| { | |
| protected ScriptEngine engine; | |
| protected ScriptContext context; | |
| public Session(ScriptEngineManager m) | |
| { | |
| engine = m.getEngineByName("js"); | |
| ScriptContext o_context = engine.getContext(); | |
| context = new SimpleScriptContext(); | |
| // context.setReader(o_context.getReader()); | |
| // context.setWriter(o_context.getWriter()); | |
| engine.setContext(context); | |
| } | |
| public Object eval(String s) throws ScriptException | |
| { | |
| return engine.eval(s); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment