简体   繁体   English

用Java获取第三方库版本

[英]get third party library versions in Java

In Python, after importing libraries, you can easily get their version numbers. 在Python中,导入库后,您可以轻松获取其版本号。 For example for json , you can easily get its version by using json.__version__ . 例如,对于json ,您可以使用json.__version__轻松获取其版本。 Is there a way in Java that can do the same thing? Java中有没有办法可以做同样的事情?

There is a standard, but it's not commonly used. 有一个标准,但它并不常用。 You may well be able to pull version info out of the jar's MANIFEST.MF file, but that will be particular to a library/vendor etc. Hopefully if you're only interested in a few particular libraries, then you can accommodate whatever notation they've adopted. 您可能能够从jar的MANIFEST.MF文件中提取版本信息,但这对于库/供应商等是特定的。希望如果您只对几个特定的​​库感兴趣,那么您可以适应任何符号已经采纳了。

If the third party library has properly configured its manifest, you can use Package.isCompatibleWith(String) (preferred) or Package.getSpecificationVersion() (less desirable). 如果第三方库已正确配置其清单,则可以使用Package.isCompatibleWith(String) (首选)或Package.getSpecificationVersion() (不太理想)。 The latter is less desirable since you'd have to do the numeric matching yourself. 后者不太理想,因为你必须自己进行数字匹配。

For instance: 例如:

Class<?> thirdPartyClass = org.apache.log4j.Logger.class;
if (thirdPartyClass.getPackage().isCompatibleWith("2.0")) {
    // Do stuff specific to Log4j 2
}

However, a lot of third party products don't bother setting the Specification-Version line in their jar's manifest, or worse, they set it incorrectly. 但是,很多第三方产品都不打扰在jar的清单中设置Specification-Version行,或者更糟糕的是,它们设置错误。 (JBoss has been a big offender in this regard historically, even going so far as to replace other third parties' specification versions with invalid ones.) The contract of the manifest is that a specification version must contain only digits and non-consecutive periods, and must start and end with a digit, so straightforward numeric comparisons can be performed. (JBoss在历史上一直是这方面的大罪犯,甚至用其他第三方的规范版本替换为无效版本。)清单的合同是规范版本必须只包含数字和非连续句点,并且必须以数字开头和结尾,因此可以执行简单的数字比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM