AhHaHaHa!!! I found out how to do it. This question was so inspirational that I had to find a solution, and here it is:
Code:
//file: RealTimeClassCreation.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLClassLoader;
/*
* ClassCreationMain.java
*
* Created on July 27, 2005, 6:49 PM
*/
/**
* @author Zodoz
*/
public class ClassCreationMain {
BufferedWriter out;
public ClassCreationMain() throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What do you want to say?");
String sayWhat = in.readLine();
//create the source file
File f = new File ("SayClass.java");
out = new BufferedWriter(new FileWriter(f));
write("public class SayClass extends TestSay {");
write("\tpublic String getText() {");
write("\t\treturn \""+sayWhat+"\";");
write("\t}");
write("}");
out.close();
/*****************************
*java source file is created
*****************************/
File f2 = new File ("");
URL url = new URL("file:"+f2.getAbsolutePath()+"\\");
URLClassLoader loader = new URLClassLoader(new URL[] { url }); //url is location
//that the classes can be found
Process p = Runtime.getRuntime().exec("javac -classpath build/classes SayClass.java"); //make sure your system path is setup to run javac
/*******************************************
* use if you want to see any errors:
*
* BufferedReader pIn = new BufferedReader(new InputStreamReader(p.getErrorStream()));
* String line = "";
* while((line = pIn.readLine())!=null)
* System.out.println(line);
***********************************/
p.waitFor(); //wait to finish the process, this line is a must
Class c = loader.loadClass("SayClass"); //load the class
Object o = c.newInstance(); //create an instance of that class
TestSay ts = (TestSay)o; //typecast it to the real class that it is
System.out.println(ts.getText()); //use it
}
public void write(String write) throws Exception {
out.write(write);
out.newLine();
out.flush();
}
public static void main(String args[]) throws Exception {
new ClassCreationMain();
}
}
A simple class to test extensions:
Code:
/*
* TestSay.java
*
* Created on July 27, 2005, 8:23 PM
*/
/**
*
* @author Zodoz
*/
public abstract class TestSay {
public abstract String getText();
}
Please tell me if this works for you, and please fell free to ask any questions.
Bookmarks