Reputation: 3364
In Python, after importing libraries, you can easily get their version numbers. For example for json
, you can easily get its version by using json.__version__
. Is there a way in Java that can do the same thing?
Upvotes: 4
Views: 302
Reputation: 44345
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.
Upvotes: 2
Reputation: 272307
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.
Upvotes: 5