Access project.version from a java class in the project?

In my java library, I need to send my project version around. Right now, when I publish to maven, I have change my com.foo.Version class as well as project.version in my build.gradle.

What would be the best way to keep both in sync?

task generateSources {
  outputDir = file("$buildDir/generated-src")
  outputs.dir outputDir
  doFirst {
    outputDir.exists() || outputDir.mkdirs()
    new File(outputDir, "com.foo.Version.java").write("public class Version { private static final String VERSION = \"$project.version\"; }")
  }
}
compileJava.dependsOn generateSources
compileJava.source generateSources.outputs.files, sourceSets.main.java
task generateSources {
  outputDir = file("$buildDir/generated-src")
  outputs.dir outputDir
  doFirst {
    outputDir.exists() || outputDir.mkdirs()
    new File(outputDir, "com.foo.Version.java").write("public class Version { private static final String VERSION = \"$project.version\"; }")
  }
}
compileJava.dependsOn generateSources
compileJava.source generateSources.outputs.files, sourceSets.main.java
task generateSources {
  outputDir = file("$buildDir/generated-src")
  outputs.dir outputDir
  doFirst {
    def srcFile = new File(outputDir, "com/foo/Version.java")
    srcFile.parentFile.mkdirs()
    srcFile.write("""
package com.foo;
public class Version {
   public static String getVersion() { return "$project.version"; }
}
""")
  }
}
compileJava.dependsOn generateSources
compileJava.source generateSources.outputs.files, sourceSets.main.java

I used a modified version of your answer to solve my problem:

task generateSources {
    outputDir = file("$buildDir/../src/main/java/com/foo")
    outputs.dir outputDir
    doFirst {
        outputDir.exists() || outputDir.mkdirs()
        def srcFile = new File(outputDir, "Version.java")
        srcFile.write(
"""package com.foo;
  public class Version {
    static final String VERSION = "$project.version";
}
""")
    }
}
  compileJava.dependsOn generateSources
compileJava.source generateSources.outputs.files, sourceSets.main.java

Thanks!

I think it’s much better to have a separate directory for generated sources rather than generating files in src/main/java. Generating to src/main/java is a bit dangerous. The good thing about generating under $buildDir is that it gets cleaned in a gradle clean.

Also, a folder is much easier (and more future proof) to ignore from source control (svn / git) than individual files.

The thing is that I want to overwrite as well be included in git. We want to make sure the Version is always up-to-date since it’s common to update one and not the other. There isn’t any critical code in this class either so there won’t be anything lost.

A common approach is to generate a properties file (or just substitute the version value in that file) and read that from the Java class.