You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java开发Gradle插件时如何获取指定依赖对应的jar文件

实现步骤

1. 定位并解析目标依赖配置

首先你需要获取你要处理的依赖配置(比如implementation、api等常用配置),在Gradle完成依赖解析后获取所有已解析的制品:

// 假设你已经拿到Project实例
project.afterEvaluate(p -> {
    // 获取指定要处理的配置名,可根据需求修改
    Configuration config = p.getConfigurations().getByName("implementation");
    ResolvedConfiguration resolvedConfig = config.getResolvedConfiguration();
    // 获取所有一级依赖的制品
    Set<ResolvedArtifact> artifacts = resolvedConfig.getResolvedArtifacts();
});

2. 过滤定位依赖A对应的Jar文件

遍历已解析的制品集合,根据坐标匹配找到你需要的依赖A,直接获取对应的文件对象:

for (ResolvedArtifact artifact : artifacts) {
    ModuleVersionIdentifier id = artifact.getModuleVersion().getId();
    // 匹配依赖A的groupId、artifactId,比如A的坐标是com.example:lib-a
    if ("com.example".equals(id.getGroup()) && "lib-a".equals(id.getName())) {
        File jarFile = artifact.getFile();
        // 此处拿到了依赖A的Jar文件,接下来读取内部的dependency.json
        processDependencyJson(jarFile, p);
        break;
    }
}

3. 读取Jar内的dependency.json并动态添加依赖

通过JarFile读取Jar包内的指定文件,解析后将新依赖添加到项目配置中:

private void processDependencyJson(File jarFile, Project project) {
    try (JarFile jar = new JarFile(jarFile)) {
        JarEntry jsonEntry = jar.getJarEntry("dependency.json");
        if (jsonEntry == null) {
            return;
        }
        // 读取json内容
        try (InputStream is = jar.getInputStream(jsonEntry)) {
            String jsonContent = new String(is.readAllBytes(), StandardCharsets.UTF_8);
            // 此处可使用Jackson/Gson等解析json,拿到要添加的依赖坐标
            List<DependencyDesc> deps = parseJson(jsonContent);
            // 动态添加依赖到配置
            for (DependencyDesc dep : deps) {
                project.getDependencies().add("implementation", dep.getGroup() + ":" + dep.getName() + ":" + dep.getVersion());
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("读取dependency.json失败", e);
    }
}

注意事项

  • 要在afterEvaluate阶段执行依赖解析逻辑,避免配置未完成解析导致获取不到完整的依赖列表
  • 如果需要适配更高版本的Gradle,建议使用惰性的Provider API替代afterEvaluate提升兼容性
  • 动态添加的依赖需要确保在编译、测试等关联任务正确依赖你的插件逻辑,避免依赖加载顺序问题

内容的提问来源于stack exchange,提问作者LeeGod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:09:01