Replace class file in jar

I have third party jar (several jars) and I need to make change in one class and replace it in this jar.

apply plugin: 'java'

version = "1.3.4"
group = "com.thirdparty"
archivesBaseName = "Base"

ext.baseFiles = [
    'com/thirdparty/base/**',
]

ext.extFiles = [
    'com/thirdparty/ext/**',
]

jar {
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
    excludes.addAll(project.ext.extFiles)
    from(zipTree("path/to/original/Base.jar"))
}

task buildExt(type: Jar, dependsOn: "build") {
    baseName = "Ext"
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
    excludes.addAll(project.ext.baseFiles)
    from(zipTree("path/to/original/Ext.jar"))
}

In the main sources set I have java files that I wanted to modify, compile and put into original jar. When I run gradle build then resulting Base-1.3.4.jar file is perfectly ok. Classes substituted.

But gradle buildExt make Ext-1.3.4.jar with same content as in the original jar. Classes not substituted.

Demo project in zip archive: http://rgho.st/8WRtY2blC

Sounds like you want my monkey patch plugin

Just declare a target to patch and put overrides in src/main/java and src/main/resources. The resultant artifact contains has the same transitive dependencies as the target so it’s a drop in replacement

Interesting, but I already find solution. Custom task of type Jar does not include project compiled classes by default. They needed to be included explicitly:

task buildExt(type: Jar, dependsOn: "build") {
    baseName = "Ext"
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
    excludes.addAll(project.ext.baseFiles)
    from(sourceSets.main.output.classesDirs) // <-- HERE
    from(zipTree("path/to/original/Ext.jar"))
}

This approach will work but you’ll lose the transitive dependency information from the target jar so you’ll need to manually declare these dependencies (if any) wherever you use the patched jar

You right. But this is acceptable to me in current circumstance.