在运行时获取 jar 版本

2022-09-01 21:58:33

我想知道是否可以在运行时检索类来自的jar的版本号?

我知道有可能找到类来自的jar:

MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();

但是版本呢?

(假设它不在文件名中:))


答案 1

试试这个,它可能会有所帮助:

String s = new String();
System.out.println(s.getClass().getPackage().getSpecificationVersion());
System.out.println(s.getClass().getPackage().getImplementationVersion());

输出:

1.7
1.7.0_25

答案 2
import javax.mail.internet.InternetAddress;

/**
Display package name and version information for javax.mail.internet.
*/
public final class ReadVersion {
  public static void main(String... aArgs){
    ReadVersion readVersion = new ReadVersion();
    readVersion.readVersionInfoInManifest();
  }

  public void readVersionInfoInManifest(){
    InternetAddress object = new InternetAddress();
    Package objPackage = object.getClass().getPackage();
    //examine the package object 
    String name = objPackage.getSpecificationTitle();
    String version = objPackage.getSpecificationVersion();
    //some jars may use 'Implementation Version' entries in the manifest instead
    System.out.println("Package name: " + name);
    System.out.println("Package version: " + version);
  }
}