How do you run a string as code? [duplicate]

2019-06-11 22:16发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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.



回答4:

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.



回答5:

Take a look at Koala Dynamic Java which takes text and dynamically compiles and runs it.