'How to get source code directory in Gradle plugin?
I want to get the directory of Java files in a Groovy plugin.
For example, I have a Java file in a directory:
"/gradleProject/src/main/java/com/file.java"
How can I get:
"src/main/java"
In Maven there is Build.getSourceDirectory()
, what is the equivalent in Gradle?
Solution 1:[1]
Further to Rene's answer, the groovy DSL makes it easy to get the SourceSet
SourceSet mainSourceSet = project.sourceSets.main
In java this is a little bit more verbose
SourceSet mainSourceSet = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().getByName("main");
Solution 2:[2]
In Gradle, those source folders are managed by SourceSet
s, that are brought to you by the Java plugin. The java plugin adds two sourceSets named main
and test
.
once the java plugin is applied, you can access those sourceSets and their properties (e.g. the folders you're looking) simply by name: project.sourceSets.main.srcDirs
- this will give you all the configured source directories for the main sourceSet in your project.
Solution 3:[3]
The latest way to do this, using the Kotlin DSL:
val javaExt = project.extensions.getByType(JavaPluginExtension::class.java)
val mainJavaSource = javaExt.sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | lance-java |
Solution 2 | Rene Groeschke |
Solution 3 | Brad Mace |