import java.io.*;
public class DynamicDate {
public static void main(String[] args) throws Exception {
/* ------------- Write the Java code ------------- */
String code = "public class DateTeller implements Teller {\n"
+ "public String tell(String name) {\n "
+ "return \"Hello \" + name + \". \" + \"The time is \" + new java.util.Date(); "
+ "}}";
File javaFile = new File("DateTeller.java");
FileWriter fwriter = new FileWriter(javaFile);
fwriter.write(code);
fwriter.close();
/* ------------------------------------------------ */
/* ------------- Compile the code ------------- */
Process compileProc = Runtime.getRuntime().exec("javac -classpath . DateTeller.java");
compileProc.waitFor(); //Wait for the process to terminate
if(compileProc.exitValue()!=0) {
System.out.println("Compile exit status: " + compileProc.exitValue());
System.out.println("Compile error:");
printStream(compileProc.getErrorStream());
}
/* ------------------------------------------------ */
/* ------------- Load the class ------------- */
Class tellerClass = Class.forName("DateTeller");
/* ------------------------------------------------ */
/* ------------- Delete the files ------------- */
javaFile.delete();
new File("DateTeller.class").delete();
/* ------------------------------------------------ */
/* ------------- Instantiate the class ------------- */
Teller teller = (Teller)(tellerClass.newInstance());
/* ------------------------------------------------ */
/* ------------- Invoke the interface method ------------- */
System.out.println(teller.tell("Snoopy"));
/* ------------------------------------------------ */
}
public static void printStream(InputStream stream) throws IOException {
byte read = 0;
while((read=(byte)stream.read())>=0) {
System.err.print((char)read);
}
}
}
|