Apache Commons JCI最佳实践(三)动态编译含包外部jar中的class引用
Apache Commons JCIadmin 发布于:2019-06-08 13:24:20
阅读:loading
章接前文,本篇文章主要实现的编译Java源文件为Class文件时含有外部jar包中的class引用,以MySQL的JDBC驱动包为例,引入“com.mysql.jdbc.Driver”类,并输出该类的字节码地址,详细实现参考如下:
package cn.chendd.example;
import junit.framework.TestCase;
import org.apache.commons.jci.compilers.CompilationResult;
import org.apache.commons.jci.compilers.JavaCompiler;
import org.apache.commons.jci.compilers.JavaCompilerFactory;
import org.apache.commons.jci.problems.CompilationProblem;
import org.apache.commons.jci.readers.FileResourceReader;
import org.apache.commons.jci.stores.FileResourceStore;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
/**
* @author chendd
* @date 2019/6/8 13:07
* 包含外部引用jar中class的引用
*/
public class ExternalClassCompiler extends TestCase {
public void testSimpleExternalClassCompiler() throws Exception {
String sources[] = new String[] { "cn/chendd/examples/SimpleExternalClass.java" };
File sourceDir = new File("D:\\test\\compiler");
File targetDir = new File("D:\\test\\compiler");
JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");
String jarPath = "C:\\Users\\chendd\\.m2\\repository\\mysql\\mysql-connector-java" +
"\\5.1.30\\mysql-connector-java-5.1.30.jar";
URL urls[] = new URL[]{
new File(jarPath).toURI().toURL()
};
ClassLoader classloader = new URLClassLoader(urls);
CompilationResult result = compiler.compile(sources, new FileResourceReader(sourceDir),
new FileResourceStore(targetDir) , classloader);
CompilationProblem[] errors = result.getErrors();
System.out.println(errors.length + " errors");
if(errors.length > 1){
System.out.println(Arrays.toString(errors));
}
System.out.println(result.getWarnings().length + " warns");
}
}
点赞