How to get version attribute from a gradle build to be included in runtime Swing application

I like creating a properties file during the build. Here's a way to do that from Gradle directly:

task createProperties(dependsOn: processResources) {
  doLast {
    new File("$buildDir/resources/main/version.properties").withWriter { w ->
        Properties p = new Properties()
        p['version'] = project.version.toString()
        p.store w, null
    }
  }
}

classes {
    dependsOn createProperties
}

You can always use brute force as somebody suggested and generate properties file during build. More elegant answer, which works only partially would be to use

getClass().getPackage().getImplementationVersion()

Problem is that this will work only if you run your application from generated jar - if you run it directly from IDE/expanded classes, getPackage above will return null. It is good enough for many cases - just display 'DEVELOPMENT' if you run from IDE(geting null package) and will work for actual client deployments.


Better idea is to keep the project version in gradle.properties file. All the properties from this file will be automatically loaded and can be used in build.gradle script.

Then if you need the version in your swing application, add a version.properties file under src/main/resources folder and filter this file during application build, here is a post that shows how it should be done.

version.properties will be included in the final jar, hence can be read and via ClassLoader and properties from this file can be displayed in application.