Assuming your Gradle script correctly inserts version into the jar manifest, as shown here :
version = '1.0' jar { manifest { attributes 'Implementation-Title': 'Gradle Quickstart', 'Implementation-Version': version } }
Your code will be able to get the version from the jar manifest file:
public class BuildVersion { public static String getBuildVersion(){ return BuildVersion.class.getPackage().getImplementationVersion(); } }
Alternatively, write a Gradle task to create a properties file with a version in it and include this generated properties file in the jar file, then access it using getResouceAsStream() .
Of course, you can also generate the BuildVersion.java file from the Gradle task, with the version directly embedded in the string literal, and make sure that the task runs before the compile task.
But I would suggest just using the version number that you are about to include already (the manifest file), which has full support from both Gradle for writing and for the Java Runtime to read it without any custom Gradle job or reading the Java file.
Andreas
source share