为何sourceSets.generated.java.srcDirs路径为"generated-src/antlr/main"而非"generated-src/antlr"?
generated-src/antlr/main instead of generated-src/antlr for ANTLR-generated sources in Gradle? Great question—this boils down to how Gradle's ANTLR plugin structures generated files compared to standard source set conventions. Let’s break it down clearly:
Standard source set paths rely on context
The example you referenced from the docs:sourceSets { main { java { srcDirs = ['src/java'] } resources { srcDirs = ['src/resources'] } } }Here, we’re configuring the
mainsource set directly inside its block. The pathsrc/javaworks because the block scope already tells Gradle we’re targeting themainsource set—we don’t need to append/mainto the path because the context defines which source set we’re working with.ANTLR plugin enforces source-set-specific isolation
The ANTLR plugin is built to keep generated code separate per source set (likemainvstest). By default, it outputs generated code togenerated-src/antlr/<sourceSetName>—so for themainsource set, that becomesgenerated-src/antlr/main. This separation ensures application code generated for production doesn’t get mixed with test-specific generated code, avoiding conflicts or unintended dependencies.You need to target the exact subdirectory for your use case
When you setsourceSets.generated.java.srcDirs = ["generated-src/antlr/main"], you’re telling Gradle to only include ANTLR code generated for themainsource set. If you used justgenerated-src/antlr, you’d pull in all ANTLR-generated files (including those fortestor custom source sets), which could lead to compile errors or include unwanted code in your final build.
In short: Standard source set config uses block scope to avoid repeating the source set name in paths, while the ANTLR plugin embeds the source set name in its output path to enforce isolation. Matching that exact subdirectory ensures you’re only including the generated code you need.
内容的提问来源于stack exchange,提问作者C2H6O

