Is it possible to create class programatically?

Advertisement
I want to create a class from a string that contains java code.
For example: I have the following string
String code = "class HelloWorld{
public static void main(String [] args){
System.out.println("Hello World");
I wonder if I can convert it to java class programatically on runtime and use it.
Advertisement

Replay

* Main.java
package sometest;
import java.io.FileOutputStream;
import java.lang.Runtime;
* @author Ganesh
public class Main {
/** Creates a new instance of Main */
public Main() {
* @param args the command line arguments
public static void main(String[] args) throws Exception{
// TODO code application logic here
FileOutputStream fos = new FileOutputStream("HelloWorld.java");
String code = "class HelloWorld{ " +
"public static void main(String [] args){"+
"System.out.println(\"Hello World\"); " +
fos.write(code.getBytes());
java.lang.Runtime rt = java.lang.Runtime.getRuntime();
try {
rt.exec("javac HelloWorld.java");
System.out.println("Compile OK");
}catch (Exception e) {
System.out.println("Compile not OK");
try {
rt.exec("java HelloWorld");
System.out.println("Run OK");
}catch (Exception e) {
System.out.println("Run not OK");
System.out.println("OK");
this would work?