Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java get version of maven dependency at runtime

Tags:

java

maven

Is it possible to retrieve the version of a specific maven dependency at runtime?

E.g. for the pom.xml:

<dependency>
    <groupId>foo.bar</groupId>
    <artifactId>foobar</artifactId>
    <version>1.0</version>
</dependency>

I would like to retrieve the version 1.0 of a specific dependency with artifact ID foobar.

like image 750
T A Avatar asked Apr 29 '26 22:04

T A


1 Answers

The most problematic part here is to find a JAR by its name. Unfortunately, there is no 100% reliable way for this in Java. To get a JAR by name, you need to scan classpath of the running application which may not always be present (e.g. because custom class loaders are used or module path is used instead of classpath).

But let's assume you are not using any fancy features like custom class loaders and you got your classpath which contains all your Maven dependencies. What do you need to do now? I'll try to describe a rough algorithm:

  • Retrieve paths of all JAR files from your classpath.
  • Scan each JAR file and find the file pom.properties. It's located in META-INF/maven/{groupId}/{artifactId}.
  • Find the value of the version property in pom.properties.

Again, this solution will not be completely reliable. You have to decide: do you really need the version information and for what purposes?

like image 137
ZhekaKozlov Avatar answered May 02 '26 11:05

ZhekaKozlov