73 lines
2.1 KiB
Java
73 lines
2.1 KiB
Java
package com.muyu.util;
|
||
|
||
import org.apache.logging.log4j.LogManager;
|
||
import org.apache.logging.log4j.Logger;
|
||
import org.springframework.stereotype.Component;
|
||
|
||
import javax.tools.JavaCompiler;
|
||
import javax.tools.JavaFileObject;
|
||
import javax.tools.StandardJavaFileManager;
|
||
import javax.tools.ToolProvider;
|
||
import java.io.File;
|
||
import java.util.Arrays;
|
||
import java.util.List;
|
||
|
||
/**
|
||
* @ClassName SourceCodeCompiler
|
||
* @Description 描述
|
||
* @Author YiBo.Liu
|
||
* @Date 2024/8/23 10:35
|
||
*/
|
||
public class SourceCodeCompiler {
|
||
|
||
private static final Logger log = LogManager.getLogger(SourceCodeCompiler.class.getName());
|
||
|
||
/**
|
||
* 获取系统java编译器
|
||
*/
|
||
private static JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
|
||
/**
|
||
* 获取java文件管理器
|
||
*/
|
||
private static StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
|
||
|
||
|
||
/**
|
||
* 输入编译的文件夹路径
|
||
* @param path 文件夹路径
|
||
*/
|
||
public static void javaCompilerPath(String path){
|
||
List<File> files = JavaCodeScan.getJavaFiles(path);
|
||
File[] array = files.toArray(new File[files.size()]);
|
||
javaCompiler(array);
|
||
|
||
|
||
}
|
||
|
||
|
||
public static void javaCompilerFile(String... filePath){
|
||
int filePathLength = filePath.length;
|
||
File[] files = new File[filePathLength];
|
||
|
||
for (int i = 0; i < filePathLength; i++) {
|
||
files[i] = new File(filePath[i]);
|
||
}
|
||
javaCompiler(files);
|
||
}
|
||
|
||
|
||
/**
|
||
*可以同时编译多个java源代码
|
||
* @param file
|
||
*/
|
||
public static void javaCompiler(File...file){
|
||
//通过源文件获取到想要编译的java类源代码迭代器,包括所有的内部类,其中每一个类都是一个JavaFileObjects,也被称为一个汇编单元
|
||
Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(file);
|
||
//生成编译任务
|
||
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, Arrays.asList("-d","home"), null, javaFileObjects);
|
||
//执行编译任务
|
||
task.call();
|
||
}
|
||
|
||
}
|