阅读课程的 jar 版本

问题描述 投票:0回答:0

对于 Web 服务客户端,我想使用 jar 文件中的实现标题和实现版本作为用户代理字符串。问题是如何读取 jar 的清单。

这个问题已被问过多次,但答案似乎不适用于我。 (例如阅读我自己的 Jar 清单

问题在于,简单地读取 /META-INF/MANIFEST.MF 几乎总是给出错误的结果。就我而言,它几乎总是指 JBoss。

https://stackoverflow.com/a/1273196/4222206中提出的解决方案 对我来说是有问题的,因为您必须对库名称进行硬编码才能停止迭代,然后它仍然可能意味着同一库的两个版本位于类路径上,而您只需返回第一个(不一定是正确的)命中。

解决方案https://stackoverflow.com/a/1273432/4222206 似乎仅适用于 jar:// url,但在 JBoss 中完全失败,其中应用程序类加载器生成 vfs:// url。

有没有办法让类中的代码找到它自己的清单?

我尝试了上述项目,这些项目似乎在从 java 命令行运行的小型应用程序中运行良好,但后来我想要一个便携式解决方案,因为我无法预测我的库稍后将在哪里使用。

public static Manifest getManifest() {
    log.debug("getManifest()");
    synchronized(Version.class) {
        if(manifest==null) {
            try {
                // this works wrongly in JBoss
                //ClassLoader cl = Version.class.getProtectionDomain().getClassLoader();
                //log.debug("found classloader={}", cl);
                //URL manifesturl = cl.getResource("/META-INF/MANIFEST.MF");

                URL jar = Version.class.getProtectionDomain().getCodeSource().getLocation();
                log.debug("Class loaded from {}", jar);

                URL manifesturl = null;
                switch(jar.getProtocol()) {
                    case "file":
                        manifesturl = new URL(jar.toString()+"META-INF/MANIFEST.MF");
                        break;
                    default:
                        manifesturl = new URL(jar.toString()+"!/META-INF/MANIFEST.MF");
                }


                log.debug("Expecting manifest at {}", manifesturl);
                manifest = new Manifest(manifesturl.openStream());
            }
            catch(Exception e) {
                log.info("Could not read version", e);
            }
        }
    }

代码将检测正确的 jar 路径。我假设通过修改 url 以指向清单将给出所需的结果,但是我得到了这个:

Class loaded from vfs:/C:/Users/user/Documents/JavaLibs/wildfly-18.0.0.Final/bin/content/webapp.war/WEB-INF/lib/library-1.0-18.jar
Expecting manifest at vfs:/C:/Users/user/Documents/JavaLibs/wildfly-18.0.0.Final/bin/content/webapp.war/WEB-INF/lib/library-1.0-18.jar!/META-INF/MANIFEST.MF
Could not read version: java.io.FileNotFoundException: C:\Users\hiran\Documents\JavaLibs\wildfly-18.0.0.Final\standalone\tmp\vfs\temp\tempfc75b13f07296e98\content-e4d5ca96cbe6b35e\WEB-INF\lib\library-1.0-18.jar!\META-INF\MANIFEST.MF (The system cannot find the path specified)

我检查了该路径,似乎甚至 jar 的第一个 URL(通过 Version.class.getProtectionDomain().getCodeSource().getLocation() 获得)也已经错误了。它应该是 C:\Users\user\Documents\JavaLibs\wildfly-18.0.0.Final\standalone mp fs emp empfc75b13f07296e9

java jar version wildfly manifest
© www.soinside.com 2019 - 2024. All rights reserved.