本代码并非原创,是在我以前的学习笔记里面翻阅出来的,是csdn里面一位叫路人甲的朋友在论坛里面的回复,也许在这里发出来会帮助到很多朋友.其实十分简单就不加注释了,一共就3步,生成java文件,编译java文件,运行java类,
package com.syj;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Method;
public class CreateClass {
private static String CLASS_NAME = "CreateClassTest";
private static String CLASS_FILE = CLASS_NAME + ".java";
public static void main(String args[]) {
CreateClass mtc = new CreateClass();
mtc.createClass();
System.out.println("javac " + CLASS_FILE);
mtc.compileClass();
System.out.println("java " + CLASS_NAME);
mtc.runClass();
}
public void createClass() {
try {
new File(CLASS_FILE).delete();
FileWriter aWriter = new FileWriter(CLASS_FILE, true);
aWriter.write("public class " + CLASS_NAME + "{");
aWriter.write("public void println() {");
aWriter.write("System.out.println("=" + CLASS_NAME + "=");");
aWriter.write("}}");
aWriter.flush();
aWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void compileClass() {
String filePath = new File(CreateClass.class.getClassLoader()
.getResource("").getFile()).getAbsolutePath();
String[] source = { "-d", filePath, new String(CLASS_FILE) };
System.out.println("javac out:"
+ com.sun.tools.javac.Main.compile(source));
}
public void runClass() {
try {
Class params[] = {};
Object paramsObj[] = {};
Class testClass = Class.forName(CLASS_NAME);
Object iClass = testClass.newInstance();
Method thisMethod = testClass.getDeclaredMethod("println", params);
thisMethod.invoke(iClass, paramsObj);
} catch (Exception e) {
e.printStackTrace();
}
}
}
需要引入%JAVA_HOME%\lib\tools.jar;这也是我遇到的tools.jar的唯一一个用途呵呵.