手动将java文件编译成class文件

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:16   2613   0
/** 
 * @Description: 编译java文件
 * @author muzb
 * @date 2019年7月1日 上午9:42:16 
 * @param classRootPath class文件存放的根目录,com目录的上一层
 * @param javaFileList 待编辑的java文件集合
 * @return void 
 */
 private static void compileJavaFile(String classRootPath, List<File> javaFileList) throws Exception {
  List<String> paths = new ArrayList<String>();
  for(File file : javaFileList){
   paths.add(file.getAbsolutePath());
  }
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
  StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, Charset.forName("UTF-8"));
  Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(paths);
  String libRootPath = "";//依赖jar包所在路径
  StringBuilder classPath = new StringBuilder();//编译依赖的class文件和jar包
  classPath.append(classRootPath).append(";");
  if("develop".equalsIgnoreCase(Global.env)){//开发环境
   libRootPath = BaseVo.class.getProtectionDomain().getCodeSource().getLocation().getFile();
   try {
    libRootPath = java.net.URLDecoder.decode(libRootPath, "UTF-8").replaceFirst("/", "").substring(0, libRootPath.indexOf("/com/"));
   } catch (UnsupportedEncodingException e1) {
    e1.printStackTrace();
   }
   classPath.append(libRootPath).append("org\\springframework\\spring-web\\4.0.0.RELEASE\\spring-web-4.0.0.RELEASE.jar;");
   classPath.append(libRootPath).append("org\\springframework\\spring-beans\\4.0.0.RELEASE\\spring-beans-4.0.0.RELEASE.jar;");
   classPath.append(libRootPath).append("org\\springframework\\spring-context\\4.0.0.RELEASE\\spring-context-4.0.0.RELEASE.jar;");
  }else if("product".equalsIgnoreCase(Global.env)){//生产环境
   libRootPath = classRootPath.substring(0, classRootPath.length()-7)+"lib\\";
   classPath.append(libRootPath).append("spring-web-4.0.0.RELEASE.jar;");
   classPath.append(libRootPath).append("spring-beans-4.0.0.RELEASE.jar;");
   classPath.append(libRootPath).append("spring-context-4.0.0.RELEASE.jar;");
  }
  //-d:输出class文件路径 -cp:依赖的class文件和jar包路径
  Iterable<String> options = Arrays.asList("-d", classRootPath,"-cp",classPath.toString()); //编译选项
  
  JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);
  boolean result = task.call();
  if(!result){
   //编译结果为false,输出编译出错信息
   for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics()) {
    logger.error(diagnostic.getSource().toString()+"/"+diagnostic.getLineNumber()+"/"+diagnostic.getMessage(null));
   }
  }
  try {
   fileManager.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP