Excluding and Replacing Class Files in a JAR

Hi there. I’m using Gradle 7.6 and am trying to replace a .class file in a .jar with a different .class file; it’s a class with Version information that is created by other Gradle tasks (one task to replace a String in the file, another to compile it). However, I can’t get the jar task to exclude the original class file.

task jar(type: Jar, overwrite: true) {
    from(compileJava.destinationDirectory.get()) {
        exclude 'foo/bar/Version.class'
    }
    from(compileVersion.destinationDirectory.get()) {
        include 'foo/bar/Version.class'
    }
    // other stuff
}

However, the generated .jar file now contains both version classes.

The only way I found to exclude the original Version.class is to use exclude at the task level, i.e.

task jar(type: Jar, overwrite: true) {
    exclude 'foo/bar/Version.class'
    from(compileVersion.destinationDirectory.get()) {
        include 'foo/bar/Version.class'
    }
    // other stuff
}

However, the .jar file generated by this now does not contain any Version.class.

Notable is that the .jar file created by the first snippet above contains every class file in duplicate which I am assuming is due to the jar task already including the output of the compileJava task by default (this is a Java project). So, I’m guessing my problem can be solved by disabling this default, or by removing the default source files of the jar task somehow.

How would I proceed?

Thanks,
Bombe

To simply answer your question, I could say use setFrom([]) to clear the already added things.

But actually, there is so much wrong in that little snippet, …

overwrite: true is almost always a bad idea, instead configure the task that is already added.

Do not create tasks using that syntax, it works against task configuration avoidance.

Do not try to exclude the one class file and replace it by another, but right away make the class file the correct one.
For example have a task that generates that file to some directory and then register this generation task as srcDir for the main source set.
Then for example also other tasks needing sources see the right version and automatically have the necessary task dependencies like a sources jar task and so on.

To just name a few.