Lets say i have this String: String run = "System.out.println\(\"Hello\"\)"
. What i want to do is run what is in the string to output Hello
in console.
Maybe there is a method like String.run()?

- 13
- 1
- 4
3 Answers
Try BeanShell , build your app with jar library.
import bsh.Interpreter;
private void runString(String code){
Interpreter interpreter = new Interpreter();
try {
interpreter.set("context", this);//set any variable, you can refer to it directly from string
interpreter.eval(code);//execute code
}
catch (Exception e){//handle exception
e.printStackTrace();
}
}

- 344
- 6
- 21
-
Thanks, I will try that – trainz-are-kul Nov 13 '16 at 18:02
Maybe in Java 9 you could use the REPL but as it's not there yet You would need to * create a temporary file with a class with a know to You API * run javac on it and compile it * load the compiled class with a class loader * run the code
If You want to do is running dynamically defined scripts in Your code then You could use Nashorn and JavaScript. It would do what You want. Also You could use Groovy in your project instead of Java - the syntax is similar to Java but Groovy is a dynamic language.

- 140
- 7
No, you cannot do it and there's no method to run this command in String
. Anything withing the double quotes becomes String
literals only and compiler doesn't take care of any command written in that.

- 608
- 4
- 9