A need that we often meet is how to know what version of the application we are running, so we can know what features the application is supporting up to this version. In Java, depending on what application you are using, Web application or Desktop application, the way to get version information of the application will be different. For Java Desktop or Java Console applications, you can store and get the application’s version information from the META-INF/MANIFEST.MF file inside the application’s jar file.
For example, I have a Java Console application that when run will print the words “Hello from Huong Dan Java”:
I used Maven Shade Plugin to build this application, and when building the application, I added some information related to the application in the META-INF/MANIFEST.MF file inside the jar file as follows:
1 2 3 4 5 6 7 8 9 10 11 |
Manifest-Version: 1.0 Archiver-Version: Plexus Archiver Created-By: Apache Maven 3.6.3 Built-By: khanh Build-Jdk: 15.0.1 Main-Class: com.huongdanjava.mavenshadeplugin.Application Implementation-Title: maven-shade-plugin-example Implementation-Vendor-Id: com.huongdanjava Implementation-Version: 0.0.1-SNAPSHOT Specification-Title: maven-shade-plugin-example Specification-Version: 0.0.1-SNAPSHOT |
Among these, the “Implementation-Version” header information contains information about the version of the application.
To get this information and display it to the application, you can use the following code:
1 2 3 4 5 6 7 8 |
public String getVersion() throws IOException { URLClassLoader cl = (URLClassLoader) Application.class.getClassLoader(); URL url = cl.findResource("META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(url.openStream()); Attributes attr = manifest.getMainAttributes(); return attr.getValue("Implementation-Version"); } |
with class Application being any class of the application.
My example is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.huongdanjava.mavenshadeplugin; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.apache.commons.lang3.StringUtils; public class Application { public static void main(String[] args) throws IOException { String version = getVersion(); System.out.println(StringUtils .capitalize("hello from Huong Dan Java. Application version is " + version)); } private static String getVersion() throws IOException { URLClassLoader cl = (URLClassLoader) Application.class.getClassLoader(); URL url = cl.findResource("META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(url.openStream()); Attributes attr = manifest.getMainAttributes(); return attr.getValue("Implementation-Version"); } } |
then when you rebuild the application and run it, you will see the following results: