Execute Java code in Java


Possible Duplicate:
Convert String to code in Java
Dynamic code execution on Java

I have a String containing :
"for(int i=0 ; i<5 ; i ){System.out.println(\"*\");}"
Can I execute the code in this String in Java?


Since Java 6, you can compile and run a Java compilation unit defined as a String or a File using standard APIs in the SDK (a compilation unit is basically everything that goes inside a .java file - package, imports, classes/interfaces/enumerations), take a look at this example. You can't run an arbitrary Java snippet like the one in your question, though.

If at all possible, it'd be a better idea to embed a different scripting language that allows you to run snippets of code from a Java program - for example, JavaScript, Groovy, MVEL, BeanShell, etc.