인터냇에서 찾은 미국사람의 싸이트에서 수정을 하고, 올린 글임..
제대로 컴파일되게 했다..
시간을 이용하여, 파일을 만들고. 그 파일을 실시간으로 컴파일하는 샘플 예제이다.
import java.io.*;
import java.util.*;
import java.lang.reflect.*;
import com.sun.tools.javac.Main;
/**
* author @knight
*/
public class MakeTodayClass {
Date today = new Date();
String todayMillis = Long.toString(today.getTime());
String todayClass = "z_" + todayMillis;
String todaySource = todayClass + ".java";
public static void main (String args[]){
MakeTodayClass mtc = new MakeTodayClass();
mtc.createIt();
if (mtc.compileIt()) {
System.out.println("Running " + mtc.todayClass + ":\n\n");
mtc.runIt();
}
else
System.out.println(mtc.todaySource + " is bad.");
}
public void createIt() {
try {
FileWriter aWriter = new FileWriter(todaySource, true);
aWriter.write("public class "+ todayClass + "{");
aWriter.write(" public void print() {");
aWriter.write(" System.out.println(\""+todayMillis+"\");");
aWriter.write(" }}\n");
aWriter.flush();
aWriter.close();
}
catch(Exception e){
e.printStackTrace();
}
}
public boolean compileIt() {
try {
String [] source = { new String(todaySource)};
com.sun.tools.javac.Main main = new com.sun.tools.javac.Main();
main.compile(source);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public void runIt() {
try {
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(todayClass);
Object iClass = thisClass.newInstance();
Method thisMethod = thisClass.getDeclaredMethod("print", params);
thisMethod.invoke(iClass, paramsObj);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
'java core' 카테고리의 다른 글
jdk 5.0 Annotation Test Code (0) | 2005.05.11 |
---|---|
[펌] RMI(Remote Method Invocation) (0) | 2005.05.11 |
jar (0) | 2005.04.25 |
Runtime in jdk5.0 (0) | 2005.03.26 |
Annotation (0) | 2005.03.18 |