欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-07 12:11:37
...
/** 
	* @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();
		}
	}

 

相关标签: 编译