Run code from a string in Java

java

Solution

If the code is in JavaScript then you can run it with JavaScript engine:

Object res = new ScriptEngineManager().getEngineByName("js").eval(str);

JavaScript engine is part of Java SE since 1.6. See this guide http://download.java.net/jdk8/docs/technotes/guides/scripting/programmer_guide/index.html for details

Problem

For debug reasons, I want to be able to run code that is typed in through the console. For example: ``` BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while(true){ String str = br.readLine(); //This can return 'a = 5;','b = "Text";' or 'pckg.example.MyClass.run(5);' if(str == null) return; runCode(str); //How would I do this? } ```

Original source

Related problems