Java编译器使用

引入依赖

1
2
3
dependencies {
compile 'org.apache.commons:commons-jci-eclipse:1.1'
}

实例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static void main(String[] args) {
JavaCompiler javaCompiler = new JavaCompilerFactory().createCompiler("eclipse");
//源码目录
File srcDir = FileUtils.getFile(FileUtils.getUserDirectoryPath() + "/workspace/temp/demo/src/main/test");
File tarDir = FileUtils.getFile(FileUtils.getUserDirectoryPath() + "/workspace/temp/demo/src/main/test");
//源码文件列表
List<File> fileList = (List<File>) FileUtils.listFiles(srcDir, new String[]{"java"}, true);
String[] sources = new String[fileList.size()];
int i = 0;
for (File file : fileList) {
sources[i] = file.getAbsolutePath().replace(FileUtils.getUserDirectoryPath() + "/workspace/temp/demo/src/main/test/", "");
i++;
}
ClassLoader loader = Thread.currentThread().getContextClassLoader();
JavaCompilerSettings settings = javaCompiler.createDefaultSettings();
settings.setWarnings(true);
settings.setSourceEncoding("utf-8");
settings.setSourceVersion("1.7");
settings.setTargetVersion("1.7");
CompilationResult result = javaCompiler.compile(sources, new FileResourceReader(srcDir), new FileResourceStore(tarDir), loader, settings);
System.out.println(result.getErrors().length + " errors");
System.out.println(result.getWarnings().length + " warnings");
}