public String compile(String srcFiles[]) {
//StringWriter err = new StringWriter();
//PrintWriter errPrinter = new PrintWriter(err);
ByteArrayOutputStream err=new ByteArrayOutputStream();
String args[] = buildJavacArgs(srcFiles);
//int resultCode = com.sun.tools.javac.Main.compile(args, errPrinter);
logger.warn("Dyna Complie Java Source:---->"+args);
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if(compiler==null){
throw new NullPointerException("ToolProvider.getSystemJavaCompiler() return null,please use JDK replace JRE!");
}
int resultCode = compiler.run(null, null, err, args);
return (resultCode == 0) ? null : err.toString();
}
参数设置正确了
private String[] buildJavacArgs(String srcFiles[]) {
ArrayList args = new ArrayList();
if (classpath != null) {
args.add("-classpath");
args.add(classpath);
}
if (outputdir != null) {
args.add("-d");
args.add(outputdir);
}
if (sourcepath != null) {
args.add("-sourcepath");
args.add(sourcepath);
}
if (bootclasspath != null) {
args.add("-bootclasspath");
args.add(bootclasspath);
}
if (extdirs != null) {
args.add("-extdirs");
args.add(extdirs);
}
if (encoding != null) {
args.add("-encoding");
args.add(encoding);
}
if (target != null) {
args.add("-target");
args.add(target);
}
for (int i = 0; i < srcFiles.length; i++) {
args.add(srcFiles[i]);
}
return (String[]) args.toArray(new String[args.size()]);
}
/**
* Extracts a classpath string from a given class loader. Recognizes only
* URLClassLoader.
*/
private static String extractClasspath(ClassLoader cl) {
StringBuffer buf = new StringBuffer();
while (cl != null) {
if (cl instanceof URLClassLoader) {
URL urls[] = ((URLClassLoader) cl).getURLs();
for (int i = 0; i < urls.length; i++) {
if (buf.length() > 0) {
buf.append(File.pathSeparatorChar);
}
String s = urls[i].getFile();
try {
s = URLDecoder.decode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
continue;
}
File f = new File(s);
// f.isFile()
buf.append(f.getAbsolutePath());
}
}
cl = cl.getParent();
}
return buf.toString();
}
创建load上述class的ClassLoader时,指定的load class的路径要和上面编译的输出路径一致
classLoader = new URLClassLoader(new URL[] { binDir.toURL() },
parentClassLoader);
后面就可以用特定的ClassLoader来加载class文件了,再后面就可以newInstance了。