The
java.lang.Package
class contains version information associated with a package.
Why is package version information becoming important?
- Because of a rapid increase in the no. of packages in Java library.
- Sometimes, a Java program may need to know what version of a package is available.
For Example:
If you want to know which
version of
java.util
you are currently using, you can pass the package name as an argument to
getPackage()
method and then invoke
getImplementationVersion()
on the Package object as shown below:
Package pkg = Package.getPackage( "java.util" );
System.out.println( pkg.getImplementationVersion() );
Output: 1.7.0_51
NOTE: Output indicates the version of
java.util
package in your system. Here, it is 1.7 and update 51, which is likely to be the version of JDK in your system.
Some important methods defined by Package
:
The following program demonstrates
getName()
and
getImplementationVersion()
methods of Package class.
Demonstration of getName and getImplementationVersion methods
class PackageClassDemo
{
public static void main(String arg[])
{
// Get all the packages that this program is currently aware of.
Package[] pkgs = Package.getPackages(); // LINE A
// Display related information about each of these packages in pkgs array
for( int i = 0; i < pkgs.length; i++ )
{
System.out.println( pkgs[i].getName() + " ---> " +
pkgs[i].getImplementationVersion() );
}
}
}
OUTPUTjavax.swing.tree ---> 1.7.0_51
sun.util.resources ---> 1.7.0_51
java.net ---> 1.7.0_51
sun.awt.image ---> 1.7.0_51
sun.reflect.misc ---> 1.7.0_51
------------------------------------
------------------------------------
------------------------------------
DESCRIPTIONOutput is very long. Only a part of it is shown here.
Here, we are collecting the package info. known to this class in a Package
array using getPackages()
method (LINE A
). Then, we are iterating over this array and displaying corresponding name and version info. of each package.
THINGS TO TRY
- Consider the above program again. Try to use
getImplementationTitle()
and getImplementationVendor()
methods as well in the SOP statement and observe the related info. displayed by these methods.
- Also try to use
getSpecificationTitle()
, getSpecificationVendor()
and getSpecificationVersion()
methods in the same way.
- Try to obtain information related to a specific package, say
javax.swing
, by passing it as an argument to getPackage()
method as shown earlier.