本想测试下动态编译结果报错baidu的答案几乎都是相互抄袭没解决问题
贴代码
package top.demo.com;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class Test {
public static void main(String argv[]) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//String clstr="public class Demo{ public static void main(String argv[])"
// + " {System.out.println(\"这是测试动态编译的类\");} }";
//File file=new File("f:/Dome.class");
//System.out.println(file.createNewFile()?"创建类文件成功":"创建类文件失败");
//BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter(file));
//bufferedWriter.write(clstr);
//bufferedWriter.close();
System.out.println(System.getProperty("java.home"));
JavaCompiler compiler=ToolProvider.getSystemJavaCompiler();
System.out.println(compiler);
File file=new File("F:\\Develepment\\Environment\\JAVA\\jre\\lib\\tools.jar");
File file2=new File("F:\\Develepment\\Environment\\JAVA\\jre\\tools.jar");
System.out.println(file.exists());
System.out.println(file2.exists());
/*int res=compiler.run(null, null, null, "f:/Dome.class");
System.out.println(res==0?"动态编译成功":"动态编译失败");
URL[] url=new URL[]{new URL("file:/"+"f:/Dome.class")};
URLClassLoader loader=new URLClassLoader(url);
Class cl=loader.loadClass("Demo");
Method m=cl.getMethod("main", String[].class);
m.invoke(null, (Object)new String[] {});*/
}
}
注意 已经测试了 百度的解决方案 把tools移动了位置 可惜还是不能解决
System.out.println(System.getProperty("java.home"));
JavaCompiler compiler=ToolProvider.getSystemJavaCompiler();
System.out.println(compiler);
File file=new File("F:\\Develepment\\Environment\\JAVA\\jre\\lib\\tools.jar");
File file2=new File("F:\\Develepment\\Environment\\JAVA\\jre\\tools.jar");
System.out.println(file.exists());
System.out.println(file2.exists());
结果
F:\Develepment\Environment\JAVA\jre
null
true
true
待知情者留言解决