有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在jar中重新定位gradle依赖项的包

目前我正在使用一个包调用a.jar。不幸的是,这个jar包含一个com.example.b包,其中对com.example.b内的代码库进行了一些定制更改

现在,我想从github的b.jar中的com.example.b包中获得一些最新的酷特性

我认为最好的解决方案(不确定如何实现)是将最新的com.example.b重新定位到com.example.standalone.b,这样a.jar仍然可以使用其定制的com.exampl.b源代码,而在项目内部我可以使用com.example.standalone.b

我对shadow插件进行了研究,但它似乎是在全局范围内按包名重命名包的,因此两个JAR(a.jarb.jar)中的包(com.example.b)也会被重命名并发生冲突

我可以知道如何对特定的jar执行此操作吗,如下面的示例

implementation a.jar:1.0
implementation (b.jar:2.0) {
   rename 'com.example.b' to 'com.example.standalone.b'
}

共 (1) 个答案

  1. # 1 楼答案

    最后,我在goovy gradle中通过以下配置解决了这个问题

    
    configurations {
        relocateB // just define a separate configuration
    }
    
    
    task relocateB (type: ShadowJar) {
        def pkg = 'com.example.b' // lib to relocate
        relocate pkg, "com.example.standalone.b" // we want to relocate the above package
        configurations = [project.configurations.relocateB] // our configuration from above
        dependencies {
            // you must exclude below files in 'kotlin_module' and 'kotlin_builtins' extension, 
            // otherwise you won't be able to import `com.example.standalone.b` in kotlin files. 
            // This is a bug from Kotlin, consumed two days for me to solve. 
            // (https://youtrack.jetbrains.com/issue/KT-25709)
            exclude '**/*.kotlin_metadata'
            exclude '**/*.kotlin_module'
            exclude '**/*.kotlin_builtins'
        }
    }
    
    
    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn relocateB
    }
    
    
    
    dependencies {
        ...
        relocateB ('com.example.b:2.2.3')
        api tasks.relocateB.outputs.files
        api 'com.example.a' // original package that won't be polluted
        ...
    }