Java Run the line as normal code.

Is there a way to run a string as code? I mean, if I had a line that has the value System.out.println("Hello World) , I could run the line like regular code, then the output would be Hello World?

Example:

 String code = "System.out.println("Hello World)"; code.run(); //I know this doesn't work 

Console:

 Hello World 
0
source share
1 answer

You need the equivalent JavaScript JavaScript. There is no equivalent in Java.

Well, there is, but it is not trivial.

You can generate the full source code of the class containing this code. Sort of

 public class StuffToDynamicallyCompile { public static final void main(String[] ignored) { PUT STUFF HERE! } } 

And then programmatically call the compiler, as described in this answer , or as indicated in the comments: How to compile .java from a java program

Not an easy task. Perhaps there is a way to minimize your requirements, so you can enable an extremely limited set of commands and just execute it with the switch ("if" dothis ", then call doThis() , otherwise if" doThat ", call doThat() , and etc.).

+1
source

Source: https://habr.com/ru/post/972286/


All Articles