JAVA如何在运行时编译一个类?

使用jdk1.6提供的JavaCompiler类。使用时一定要保证你的classpath的jre是jdk1.6,不能是纯jre,不然会出问题。
public class test{
 String str = "package test;\n"
				+ "import static org.junit.Assert.assertEquals;\n"
				+ "import org.junit.Test;\n"
				+ "public class RunTest { \n" + "@Test\n"
				+ "public void testOutPutXmlExists()\n{\n" + "assertEquals(0,1);\n"
				+ "}\n" + "}";
		String basePath = System.getProperty("user.dir");
		String fileName = basePath + "\\src\\test\\RunTest.java";
		String classPath = basePath + "\\bin";
		File file = new File(fileName);
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			FileWriter fw;
			fw = new FileWriter(file);
			fw.write(str);
			fw.flush();
			fw.close();
			JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
			StandardJavaFileManager fileMgr = compiler.getStandardFileManager(
					null, null, null);
			Iterable<String> options = Arrays.asList("-d", classPath);
			Iterable units = fileMgr.getJavaFileObjects(fileName);
			CompilationTask t = compiler.getTask(null, fileMgr, null, options,
					null, units);
			t.call();
			fileMgr.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
} 

你可能感兴趣的:(java)