convert String to runtime code in java

2019-08-29 05:59发布

问题:

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.