how to check the version of jar file?

2019-01-18 07:59发布

I am currently working on a J2ME polish application, just enhancing it. I am finding difficulties to get the exact version of the jar file. Is there any way to find the version of the jar file for the imports done in the class? I mean if you have some thing, import x.y.z; can we know the version of the jar x.y package belongs to?

10条回答
放我归山
2楼-- · 2019-01-18 08:48

I'm late this but you can try the following two methods

using these needed classes

import java.util.jar.Attributes;
import java.util.jar.Manifest;

These methods let me access the jar attributes. I like being backwards compatible and use the latest. So I used this

public Attributes detectClassBuildInfoAttributes(Class sourceClass) throws MalformedURLException, IOException {
    String className = sourceClass.getSimpleName() + ".class";
    String classPath = sourceClass.getResource(className).toString();
    if (!classPath.startsWith("jar")) {
      // Class not from JAR
      return null;
    }
    String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + 
        "/META-INF/MANIFEST.MF";
    Manifest manifest = new Manifest(new URL(manifestPath).openStream());
    return manifest.getEntries().get("Build-Info");
}

public String retrieveClassInfoAttribute(Class sourceClass, String attributeName) throws MalformedURLException, IOException {
    Attributes version_attr = detectClassBuildInfoAttributes(sourceClass);

    String attribute = version_attr.getValue(attributeName);

    return attribute;
}

This works well when you are using maven and need pom details for know classes. Hope this helps.

查看更多
在下西门庆
3楼-- · 2019-01-18 08:51

You can filter version from the MANIFEST file using

unzip -p my.jar META-INF/MANIFEST.MF | grep 'Bundle-Version'

查看更多
时光不老,我们不散
4楼-- · 2019-01-18 08:52

Just to complete the above answer.

Manifest file is located inside jar at META-INF\MANIFEST.MF path.

You can examine jar's contents in any archiver that supports zip.

查看更多
成全新的幸福
5楼-- · 2019-01-18 08:56

Decompress the JAR file and look for the manifest file (META-INF\MANIFEST.MF). The manifest file of JAR file might contain a version number (but not always a version is specified).

查看更多
登录 后发表回答