简体   繁体   中英

Gradle: How to exclude a particular package from a jar?

We have a package that is related to some requirements that were removed, but we don't want to necessarily delete the code because there's a possibility it will be needed again in the future. So in our existing ant build, we've just excluded this package from being compiled in our jar. These classes do not compile due to the fact that we've also removed their dependencies, so they can't be included in the build.

I'm attempting to mimic that functionality in Gradle as follows:

jar {
    sourceSets.main.java.srcDirs = ['src', '../otherprojectdir/src']

    include (['com/ourcompany/somepackage/activityadapter/**',
                 ...
        'com/ourcompany/someotherpackage/**'])

    exclude(['com/ourcompany/someotherpackage/polling/**'])
}

Even with the exclude call above (and I've tried it without the square brackets as well), gradle is still attempting to compile the polling classes, which is causing compile failures. How do I prevent Gradle from attempting to compile that package?

This solution is valid if you don´t want to compile these packages, but if you want to compile them and exclude from your JAR you could use

// tag::jar[]
jar {
    exclude('mi/package/excluded/**')   
    exclude('mi/package/excluded2/**')  
}
// end::jar[]

If you have some sources that you don't want to be compiled, you have to declare a filter for the sources, not for the class files that are put in the Jar. Something like:

sourceSets {
    main {
        java {
            include 'com/ourcompany/somepackage/activityadapter/**'
            include 'com/ourcompany/someotherpackage/**'
            exclude 'com/ourcompany/someotherpackage/polling/**'
        }
    }
}

In 2018:

You may also use a closure or Spec to specify which files to include or exclude. The closure or Spec is passed a FileTreeElement, and must return a boolean value.

jar {
  exclude {
    FileSystems.getDefault()
      .getPathMatcher("glob:com/ourcompany/someotherpackage/polling/**")
      .matches(it.file.toPath())
  }
}

See Jar.exclude , FileTreeElement and Finding Files .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM