Possible Duplicate:
Convert String to code
I have a program that needs to be able to execute a string as code. For example, I would have a string that reads:
public void do(int a, int b){
a++;
b--;
System.out.println(a);
System.out.println(b);
}
Now, how do I get the program to execute that string?
You can wrap this string in a class and compile it with Java Compiler API. You would have to be running JDK instead of JRE.
See this similar question
This simple answer is, this can't really be done in Java. You could come up with some hacky ways of doing it by attempting to invoke the javac compiler, but I'm not sure how you would really load it in or make use of it at that point.
In some scripting languages, like Javascript and Lua, you can use 'eval' type functions that attempt to load your string and execute it.
I'm not entirely sure (it has been a long time since I've used it), but you might be able to use BeanShell to execute the Java code that is a String. Take a look at the docs for some examples.
I think the question is how do I run this program? The answer is it needs to be wrapped in a class definition, along with a "static main" function so the java command line tool can run it after it is compiled.
Take a look at Koala Dynamic Java which takes text and dynamically compiles and runs it.