Java - Run a string as normal code [duplicate]

假如想象 提交于 2019-12-20 06:25:35

问题


Is there a way to run a string as code? I mean if I had a string run having value System.out.println("Hello World) could I run the string as normal code the then output will be Hello World?

For Example:

String code = "System.out.println("Hello World)";

code.run(); //I know this doesn't work

Console:

Hello World

回答1:


You want the equivalent of JavaScript's eval. There is no equivalent in Java.

Well, there is but it's not trivial.

You can generate the full source code of a class containing that code. Something like

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

And then programatically invoke the compiler, as described in this answer, or as stated in the comments: How to compile .java file from within java program

Not a simple task. Perhaps there's a way to minimize your requirements, so you can allow an extremely limited set of commands, and just execute it with a switch ("if 'dothis' then call doThis(), else if 'doThat', call doThat(), etc.).



来源:https://stackoverflow.com/questions/24665848/java-run-a-string-as-normal-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!