Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Java code in Java [duplicate]

Tags:

java

string

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?

like image 969
Devashish Dixit Avatar asked Dec 28 '11 21:12

Devashish Dixit


2 Answers

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.

like image 66
Óscar López Avatar answered Sep 29 '22 09:09

Óscar López


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.

like image 27
Mike Nakis Avatar answered Sep 29 '22 09:09

Mike Nakis