阅读课程的jar版本

对于Web服务客户端,我想将jar文件中的Implementation-Title和Implementation-Version用作用户代理字符串。问题是如何读取罐子的清单。

这个问题已被问过多次,但是答案似乎不适用于我。 (例如Reading my own Jar's Manifest

问题在于,仅读取/Meta-INF/MANIFEST.MF几乎总是会得到错误的结果。就我而言,它几乎总是指JBoss。

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

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)

我检查了该路径,似乎罐子的第一个URL(通过Version.class.getProtectionDomain()。getcodeSource()。getLocation()获得)都已经错误了。它应该是C:\ Users \ user \ Documents \ JavaLibs \ wildfly-18.0.0.Final \ standalone \ tmp \ vfs \ temp \ tempfc75b13f07296e98 \ content-e4d5ca96cbe6b35e \ WEB-INF \ lib \ library-1.0.18.jar

所以这甚至可能指向Wildfly中的问题?

wondernuaa 回答:阅读课程的jar版本

似乎我在这里找到了一些合适的解决方案: https://stackoverflow.com/a/37325538/4222206

因此最后,该代码可以在JBoss中至少显示正确的jar版本:

this.getClass().getPackage().getImplementationTitle();
this.getClass().getPackage().getImplementationVersion();

希望我下次搜索时会找到这个答案...

本文链接:https://www.f2er.com/3136792.html

大家都在问