Java 在运行时获取 jar 版本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21724145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get jar version in runtime
提问by zibi
I'm wondering if it is possible to retrieve, in runtime, a version number of a jar from which the class comes from?
我想知道是否可以在运行时检索该类来自的 jar 的版本号?
I know its possible to find jar from which the class comes from:
我知道可以找到类来自的 jar:
MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
but what about a version?
但是一个版本呢?
(assuming its not in the file name:) )
(假设它不在文件名中:))
采纳答案by 1ac0
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);
}
}
回答by Shekhar Khairnar
Try this, it may be helpful:
试试这个,它可能会有所帮助:
String s = new String();
System.out.println(s.getClass().getPackage().getSpecificationVersion());
System.out.println(s.getClass().getPackage().getImplementationVersion());
Output:
输出:
1.7
1.7.0_25
回答by olga
Be careful using getPackage().getImplementationVersion/getSpecificationVersion()
小心使用 getPackage().getImplementationVersion/getSpecificationVersion()
getSpecificationVersion returns specVersion from Manifest. Manifest is a property of a jar and is used in sun.misc.URLClassPath as
getSpecificationVersion 从 Manifest 返回 specVersion。Manifest 是 jar 的一个属性,在 sun.misc.URLClassPath 中用作
public Manifest getManifest() throws IOException {
SharedSecrets.javaUtilJarAccess().ensureInitialization(JarLoader.this.jar);
return JarLoader.this.jar.getManifest();
}
So in case somebody use your library as dependency for fat jar, it returns the version of Manifest for fat jar.
因此,如果有人使用您的库作为 fat jar 的依赖项,它会返回 fat jar 的 Manifest 版本。