Alex S. Diaz
Alex S. Diaz

Reputation: 2667

Get jar library names used by app

How can I get all jars name used by my application?

Based on the bellow image, I would like an array that contains all jar file names, something like this:

myArray = ["log4j-1.2.17.jar","commons-io-2.4.jar","zip4j_1.3.2.jar"]

jar libraries

I have read this question, and try this:

String classpath = System.getProperty("java.class.path");
log.info(classpath);
List<String> entries = Arrays.asList(classpath.split(System.getProperty("path.separator")));
log.info("Entries " + entries);

But when I run the jar, I got this in my log file:

2015-07-10 17:41:23 INFO  Updater:104 - C:\Prod\lib\Updater.jar 
2015-07-10 17:41:23 INFO  Updater:106 - Entries [C:\Prod\lib\Updater.jar]

Bellow the same question, one of the answers says I could use the Manifest class, but how do I do this?

Upvotes: 0

Views: 1103

Answers (2)

Alex S. Diaz
Alex S. Diaz

Reputation: 2667

After trying and with the help of @lepi answer, I could read my manifest and get those jar names that I need with the following code:

URL resource;
String[] classpaths = null;
try {
    resource = getClass().getClassLoader().getResource("META-INF/MANIFEST.MF");
    Manifest manifest = new Manifest(resource.openStream());
    classpaths = manifest.getMainAttributes().getValue("Class-Path").split(" ");
    log.info(classpaths);
} catch (IOException e) {
    log.warn("Couldn't find file: " + e);
}

With this, I got an array with the string of those jar file name like this:

[log4j-1.2.17.jar, commons-io-2.4.jar, zip4j_1.3.2.jar]

And this is what I was looking for. Thanks!

Upvotes: 0

lepi
lepi

Reputation: 104

You can work with manifest entries like this:

Enumeration<URL> resources = getClass().getClassLoader()
      .getResources("META-INF/MANIFEST.MF");
   while (resources.hasMoreElements()) {
      try {
          Manifest manifest = new Manifest(resources.nextElement().openStream());
          // check that this is your manifest and do what you need or get the next one
         ...
       } catch (IOException E) {
          // handle
       }
   }

Here's a question about reading Manifest entires

reading-my-own-jars-manifest

from there, you can get all the dependencies names.

Upvotes: 2

Related Questions