我想知道是否有可能在运行时检索一个JAR文件的版本号,该JAR文件中包含了该类?
我知道可以找到包含该类的JAR文件:
MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
但是版本呢?
(假设它不在文件名中:))
我想知道是否有可能在运行时检索一个JAR文件的版本号,该JAR文件中包含了该类?
我知道可以找到包含该类的JAR文件:
MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
但是版本呢?
(假设它不在文件名中:))
试一下这个,它可能会有帮助:
String s = new String();
System.out.println(s.getClass().getPackage().getSpecificationVersion());
System.out.println(s.getClass().getPackage().getImplementationVersion());
输出:
1.7
1.7.0_25
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);
}
}
objPackage.getSpecificationVersion()
可能会返回版本为'null'的情况。
要解决这个问题,请参考:https://dev59.com/eHE85IYBdhLWcg3wkkY8 - Isuru Hemantha请小心使用getPackage().getImplementationVersion/getSpecificationVersion()
getSpecificationVersion返回来自清单的specVersion。 清单是一个jar的属性,它在sun.misc.URLClassPath中使用。
public Manifest getManifest() throws IOException {
SharedSecrets.javaUtilJarAccess().ensureInitialization(JarLoader.this.jar);
return JarLoader.this.jar.getManifest();
}
因此,如果有人将你的库用作fat jar的依赖项,则会返回fat jar的清单版本。