Android build.gradle中优化SpotBugs配置的Gradle表达式问题
The issue with your attempt is that you're trying to cast a Java Stream directly to a FileCollection, which doesn't work—Gradle needs a proper FileCollection instance that can track task dependencies and file paths correctly. Here's the correct way to achieve what you want:
Correct Implementation for Subprojects Within the Root
If subproject-one, subproject-two, etc., are actual subprojects of your root project (listed in your settings.gradle), use this code:
tasks.withType(com.github.spotbugs.SpotBugsTask) { classes = project.files(rootProject.subprojects.collect { proj -> proj.fileTree("${proj.buildDir}/intermediates/classes") }) }
Why This Works:
rootProject.subprojects.collect { ... }gathers a list ofFileTreeobjects, one for each subproject's classes directory.project.files(...)takes this list of file trees and merges them into a singleFileCollection—exactly what theclassesproperty expects. This method also ensures Gradle can track the dependencies of these files, which fixes the error you encountered.
If Your Projects Are Siblings to the Root
If those projects are sibling directories (outside your root project's folder, as your original path suggests), rootProject.subprojects won't include them. In that case, you can define a list of project paths and collect their classes directories to keep your code DRY:
tasks.withType(com.github.spotbugs.SpotBugsTask) { def siblingProjects = [ "../subproject-one/app", "../subproject-two/app", "../subproject-three/app" ] classes = project.files(siblingProjects.collect { projPath -> fileTree("${rootProject.rootDir}/${projPath}/build/intermediates/classes") }) }
Pro Tip for Android Projects
Instead of hardcoding intermediates/classes, use Gradle's built-in source set properties to reference the classes directory more reliably (this works across different Android Gradle Plugin versions):
proj.fileTree(proj.sourceSets.main.output.classesDirs)
This avoids issues if the classes directory path changes in future plugin updates.
内容的提问来源于stack exchange,提问作者Youngjae

