hugodecasta
hugodecasta

Reputation: 262

convert String to runtime code in java

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

Upvotes: 0

Views: 3023

Answers (1)

AlexR
AlexR

Reputation: 115328

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.

Upvotes: 1

Related Questions