convert String to runtime code in java

南楼画角 提交于 2019-12-25 10:00:43

问题


I'm creating a software that would execute custom code line by string SO, is there any method function or whatever you want that can do that :

String command="println("the TEST work !!!")";
magicExecMethod(command);

*and it print : the TEST work !!!

Thancks


回答1:


You have several ways to achieve this.

You can create java file by printing it line-by-line, then compile it by either invocation of compiler from command line or by calling java.lang.Compiler, then run it.

Other way is to run your line directly using Groovy - java based language that supports Java syntax and can be used in interpreter mode.

If you are not sticky to java syntax and for example can use java script instead you can use ScriptingHost and Rhino that is a part of JDK since java 1.5.



来源:https://stackoverflow.com/questions/19408837/convert-string-to-runtime-code-in-java

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