Run Java code in Java

Possible duplicate:
Convert String to Code in Java
Running Dynamic Java Code

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

+6
source share
6 answers

Starting with Java 6, you can compile and run the Java compilation unit, defined as String or File, using the standard APIs in the SDK (the compilation unit is basically everything that comes in the package .java package, import, classes / interfaces / enums ), look at an example . However, you cannot run an arbitrary Java fragment similar to the one asked in your question.

If at all possible, it would be better to introduce another scripting language that allows you to run code snippets from a Java program - for example, JavaScript, Groovy, MVEL , BeanShell , etc.

+3
source

If you turn it into a full-blown source file, you can programmatically combine it with a java compiler, but last time I checked that it is available only if the Java SDK is installed on your computer; it was not available on Java client distribution machines. Of course, this can change since then. Take a look at the com.sun.tools.javac package and you will find a java compiler there.

+2
source

Perhaps you can run this as Groovy:

http://groovy.codehaus.org/Embedding+Groovy

+2
source

There is no Java Core API function for this, but you can call javac either using Runtime.exec or using some of the "unsafe" classes from com.sun.tools.javac Here is an example:

http://juixe.com/techknow/index.php/2006/12/12/invoke-javac-at-runtime/

+1
source

I do not think you can execute a line containing Java code.

But it is worth a try if you can save this as a java source file and try to use the ProcessBuilder class to execute.

Never tried and not sure if this is the best way to do this. Therefore use it with caution :)

Good luck

Also found a similar post: Runtime class in java

+1
source

No, you cannot execute this code in your program.

0
source

Source: https://habr.com/ru/post/904632/


All Articles