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.
If you turn it into a full-blown source file, you can feed it to the java compiler programmatically, but last time I checked that was only available if you had the java SDK installed on your machine; it was not available on machines with the client distribution of Java. Of course, this may have changed since then. Look at package com.sun.tools.javac and you will find the java compiler API there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With