获取JAR文件的版本号 [英] Get a JAR File version number

查看:725
本文介绍了获取JAR文件的版本号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于集群的应用程序,如果一个或多个失败,它将保持可用,我想实现一种方法来检查Java中jar文件的版本.

I have an application used in clustering to keep it available if one or more failed and I want to implement a way to check the version of the jar file in java.

我有这段代码可以做到这一点(例如:在MyClass类中):

I have this piece of code to do that (e.g.: in the class MyClass) :

        URLClassLoader cl = (URLClassLoader) (new MyClass ())
            .getClass().getClassLoader();
        URL url = cl.findResource("META-INF/MANIFEST.MF");
        Manifest manifest = new Manifest(url.openStream());
        attributes = manifest.getMainAttributes();
        String version = attributes.getValue("Implementation-Version");

当我将jar作为应用程序运行时,当我将jar文件用作其他应用程序中的librairie时,它可以很好地工作,但是我获得了另一个应用程序的版本号.

When i run the jar as an application it works fine BUT when i use the jar file as a librairie in an other application, i get the version number of the other application.

所以我的问题是,如何获取包含MyClass的jar的清单?

So my question is, how can i get the manifest of the jar where MyClass is contained ?

NB:我对使用静态约束的解决方案不感兴趣,例如 'classLoader.getRessource("MyJar.jar")'或File("MyJar.jar")

NB : I'm not interested in solution using static constraint like 'classLoader.getRessource("MyJar.jar")' or File("MyJar.jar")

推荐答案

最后,我从朋友那里得到了解决方案:

Finally i get the solution from a friend :

    // Get jarfile url
    String jarUrl = JarVersion.class
        .getProtectionDomain().getCodeSource()
        .getLocation().getFile();

    JarFile jar = new JarFile(new File(jarUrl));
    Manifest manifest = jar.getManifest();
    Attributes attributes = manifest.getMainAttributes();

    String version = attributes.getValue(IMPLEMENTATION_VERSION) 

这篇关于获取JAR文件的版本号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆