获取app使用的jar库名称

Get jar library names used by app

如何获取我的应用程序使用的所有 jars 名称?

根据下图,我想要一个包含所有 jar 文件名的数组,如下所示:

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

我已阅读 this question,然后试试这个:

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);

但是当我 运行 jar 时,我在我的日志文件中得到了这个:

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]

同一个问题,其中一个答案说我可以使用清单 class,但我该怎么做?

您可以像这样处理清单条目:

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
       }
   }

这是一个关于完整阅读清单的问题

reading-my-own-jars-manifest

从那里,您可以获得所有依赖项名称。

在@lepi 回答的帮助下尝试后,我可以阅读我的清单并使用以下代码获取我需要的那些 jar 名称:

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);
}

有了这个,我得到了一个包含这些 jar 文件名字符串的数组,如下所示:

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

这就是我要找的。谢谢!