获取app使用的jar库名称

时间:2015-07-10 23:54:33

标签: java jar

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

基于波纹管图像,我想要一个包含所有jar文件名的数组,如下所示:

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

jar libraries

我已阅读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]

同样的问题,其中一个答案说我可以使用Manifest类,但我该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以使用以下清单条目:

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

这是关于阅读Manifest entires的问题

reading-my-own-jars-manifest

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

答案 1 :(得分:0)

尝试并在@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]

这就是我想要的。谢谢!

相关问题