簡體   English   中英

以編程方式列出包括的Java庫

[英]Programmatically list included Java libraries

我正在研究一個利用許多安全性/實用程序庫的項目。 出於安全原因,我希望能夠通知用戶我們使用了哪些庫以及它們的bin中正在運行哪個版本。 我們的許多用戶都選擇修改我們的代碼,因此我希望它以編程方式進行修改。

我試圖解析類路徑,但是當程序打包到jar中時,這似乎無濟於事。 我也嘗試過列出JAR中的所有類名,但這不傳達任何版本信息。

我們所有的庫都具有jar文件名稱中的版本。 我願意制作某種編譯時腳本。 我們使用ant和intellij構建。 螞蟻是我唯一需要支持的人,intellij只會讓生活更輕松。

如果罐子位於類路徑中,則可以使用系統屬性來獲取罐子。

  String path = System.getProperty("java.class.path");
  String[] p;
  p = path.split(";");
  for(int i=0; i< p.length; i++) {
      System.out.println(p[i]);
  }

對於上面的示例,我曾經從服務器返回所有Web應用程序庫。 您可以執行類似操作以獲取所需的罐子。

如果將它們打包到jar中,則需要從類目錄本身加載它,可以嘗試使用classloader。

 ClassLoader loader = ClassLoader.getSystemClassLoader();
 URL[] urls = ((URLClassLoader)loader).getURLs();
 for(URL url: urls){
    System.out.println(url.getFile());
 }

我能夠通過解析META-INF / maven / org / blah / pom.properties文件來做到這一點。 它僅適用於具有maven支持的庫(盡管您的項目不需要任何與maven相關的內容)。

private static HashMap<String,String> getVersionMap () {
    //Results by <lib name, version>
    final HashMap<String,String> resultMap = new HashMap<>();
    try {
        //Hack to get a ref to our jar
        URI jarLocation = new URI("jar:" + SecurityInfo.class.getProtectionDomain().getCodeSource().getLocation().toString());
        //This jdk1.7x nio util lets us look into the jar, without it we would need ZipStream
        FileSystem fs = FileSystems.newFileSystem(jarLocation, new HashMap<String,String>());

        Files.walkFileTree(fs.getPath("/META-INF/maven"), new HashSet<FileVisitOption>(), 3, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                if (file.toString().endsWith(".properties")) {
                    try {
                        List<String> data = Files.readAllLines(file, Charset.defaultCharset());
                        String id = data.get(4);
                        id = id.substring(id.lastIndexOf('=') + 1);
                        String version = data.get(2);
                        version = version.substring(version.lastIndexOf('=') + 1);
                        resultMap.put(id, version);
                    }
                    catch(Exception ignore) {}
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch(Exception ignore) {
        return new HashMap<>();
    }
    return resultMap;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM