Gnijuohz Gnijuohz - 1 year ago 57
Java Question

get third party library versions in Java

In Python, after importing libraries, you can easily get their version numbers. For example for

, you can easily get its version by using
. Is there a way in Java that can do the same thing?


If the third party library has properly configured its manifest, you can use Package.isCompatibleWith(String) (preferred) or Package.getSpecificationVersion() (less desirable). 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. (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.