Gradle:如何从jar中排除特定包?

我们有一个与已删除的某些要求相关的包,但我们不希望删除该代码,因为将来可能会再次需要它。 所以在我们现有的ant构建中,我们刚刚将这个包排除在jar中编译之外。 这些类不能编译,因为我们还删除了它们的依赖项,因此它们不能包含在构建中。

我试图在Gradle中模仿该function,如下所示:

jar { sourceSets.main.java.srcDirs = ['src', '../otherprojectdir/src'] include (['com/ourcompany/somepackage/activityadapter/**', ... 'com/ourcompany/someotherpackage/**']) exclude(['com/ourcompany/someotherpackage/polling/**']) } 

即使使用上面的exclude调用(我也尝试过没有方括号),gradle仍在尝试编译polling类,这会导致编译失败。 如何防止Gradle尝试编译该包?

如果您有一些不想编译的源,则必须为源声明一个filter,而不是为Jar中放置的类文件。 就像是:

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

如果您不想编译这些包,此解决方案是有效的,但如果您想要编译它们并从JAR中排除,则可以使用

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

2018年:

您还可以使用闭包或Spec来指定要包含或排除的文件。 闭包或Spec传递给FileTreeElement,并且必须返回一个布尔值。

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

请参阅Jar.exclude , FileTreeElement和Finding Files 。