前几天看到了 今天米事就来写一写, = = 期间遇到了两个问题:
用eclipse来写com.sun.tools找不到,以及运行时找不到文件(java.lang.ClassNotFoundException)。。
先贴代码:
- package org.yoyo.test;
- import java.io.File;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLClassLoader;
- import java.util.Scanner;
- import com.sun.tools.javac.Main;
- /**
- * 动态编译测试
- * @author YOYO
- */
- public class RuntimeCompileTest {
- /**
- * CompileMain
- */
- private static Main javac = new Main();
- /**
- * 创建临时文件存放代码
- * @param codes
- * @return
- */
- private File createFile(String codes) {
- try {
- File file = File.createTempFile("RuntimeCompile_", ".java",
- new File(System.getProperty("user.dir")));
- String className = getClassName(file);
- PrintWriter writer = new PrintWriter(file);
- writer.write("public class " + className + " {" + "/r/n");
- writer.write(" public static void main(String[] args) {" + "/r/n");
- writer.write(codes);
- writer.write(" }" + "/r/n");
- writer.write("}" + "/r/n");
- writer.flush();
- writer.close();
- return file;
- } catch (IOException e) {
- e.printStackTrace();
- return null;
- }
- }
- /**
- * 输入代码
- * @return
- */
- private String inputCode() {
- StringBuffer codes = new StringBuffer("");
- System.out.println("请输入Java代码:");
- Scanner scanner = new Scanner(System.in);
- while (scanner.hasNext()) {
- codes.append(scanner.nextLine() + "/r/n");
- }
- scanner.close();
- return new String(codes);
- }
- /**
- * 编译
- * @param fileName
- * @return
- */
- @SuppressWarnings("static-access")
- private synchronized int compile(String fileName) {
- String[] args = new String[] {"-d", System.getProperty("user.dir"), fileName};
- return javac.compile(args);
- }
- /**
- * 执行
- * @param file
- * @return
- */
- @SuppressWarnings("unchecked")
- private synchronized boolean run(File file) {
- new File(file.getParent(), getClassName(file) + ".class").deleteOnExit();
- try {
- URL url = new URL("file:/" + System.getProperty("user.dir") + ""
- + File.separator);
- URLClassLoader urlClass = new URLClassLoader(new URL[] { url });
- Class clazz = urlClass.loadClass(getClassName(file));
- Method main = clazz.getMethod("main",
- new Class[] { String[].class });
- main.invoke(null, new Object[] { new String[0] });
- return true;
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- return false;
- }
- /**
- * 获得类名
- * @param file
- * @return
- */
- private String getClassName(File file) {
- return file.getName().substring(0,
- file.getName().length() - ".java".length());
- }
- /**
- * 测试
- * @return
- */
- public boolean newTest() {
- File file = createFile(inputCode());
- if ("".equals(file.getName()) || 0 != compile(file.getName())) {
- return false;
- }
- return run(file);
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- System.out.println("Test : " + new RuntimeCompileTest().newTest());
- }
- }
com.sun.tools找不到的解决方法:在项目属性-Libraries里面加上jdk下面的tools.jar包即可。
java.lang.ClassNotFoundException引起原因:我原来用的是Class.forName(...)方法,这个方法只加载ClassPath里面的类,因此找不到。。
改成上面代码中的URLClassLoader来读取就可以了。
测试一下。。。:
请输入Java代码:
for (int i = 0; i < 26; ++i) {
System.out.print((char)('A' + i));
}
System.out.println();
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Test : true
for (int i = 0; i < 26; ++i) {
System.out.print((char)('A' + i));
}
System.out.println();
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Test : true