Java Gradle:如何从 jar 中排除特定的包?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19575474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Gradle: How to exclude a particular package from a jar?
提问by StormeHawke
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.
我们有一个与已删除的一些要求相关的包,但我们不想删除代码,因为将来可能会再次需要它。因此,在我们现有的 ant 构建中,我们只是将这个包排除在我们的 jar 中编译之外。由于我们还删除了它们的依赖项,这些类无法编译,因此它们不能包含在构建中。
I'm attempting to mimic that functionality in Gradle as follows:
我试图在 Gradle 中模仿该功能,如下所示:
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?
即使使用上面的 exclude 调用(我也尝试过不使用方括号),gradle 仍在尝试编译polling
类,这会导致编译失败。如何防止 Gradle 尝试编译该包?
采纳答案by Peter Niederwieser
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:
如果您有一些不想编译的源,则必须为源声明过滤器,而不是为放入 Jar 的类文件声明过滤器。就像是:
sourceSets {
main {
java {
include 'com/ourcompany/somepackage/activityadapter/**'
include 'com/ourcompany/someotherpackage/**'
exclude 'com/ourcompany/someotherpackage/polling/**'
}
}
}
回答by Gusa
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
如果你不想编译这些包,这个解决方案是有效的,但是如果你想编译它们并从你的 JAR 中排除,你可以使用
// tag::jar[]
jar {
exclude('mi/package/excluded/**')
exclude('mi/package/excluded2/**')
}
// end::jar[]
回答by Abhijit Sarkar
In 2018:
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.
您还可以使用闭包或规范来指定要包含或排除的文件。闭包或规范被传递一个 FileTreeElement,并且必须返回一个布尔值。
jar {
exclude {
FileSystems.getDefault()
.getPathMatcher("glob:com/ourcompany/someotherpackage/polling/**")
.matches(it.file.toPath())
}
}
See Jar.exclude, FileTreeElementand Finding Files.