149. Inspecting packages

The java.lang.Package class is our main focus when we need to obtain information about a specific package. Using this class, we can find out the package's name, the vendor that implemented this package, its title, the version of the package, and so on.

This class is commonly used to find the name of a package that contains a certain class. For example, the package name of the Integer class can be easily obtained as follows:

Class clazz = Class.forName("java.lang.Integer");
Package packageOfClazz = clazz.getPackage();

// java.lang
String packageNameOfClazz = packageOfClazz.getName();

Now, let's find the package name of the File class:

File file = new File(".");
Package packageOfFile = file.getClass().getPackage();

// java.io
String packageNameOfFile = packageOfFile.getName();
If we are trying to find the package name of the current class, then we can rely on this.getClass().getPackage().getName(). This works in a non-static context.

But if all we want is to quickly list all the packages of the current class loader, then we can rely on the getPackages() method, as follows:

Package[] packages = Package.getPackages();

Based on the getPackages() method, we can list all the packages defined by the caller's class loader, as well as its ancestors, which start with a given prefix, as follows:

public static List<String> fetchPackagesByPrefix(String prefix) {

return Arrays.stream(Package.getPackages())
.map(Package::getName)
.filter(n -> n.startsWith(prefix))
.collect(Collectors.toList());
}

If this method lives in a utility class named Packages, then we can call it as follows:

List<String> packagesSamePrefix 
= Packages.fetchPackagesByPrefix("java.util");

You will see output similar to the following:

java.util.function, java.util.jar, java.util.concurrent.locks,
java.util.spi, java.util.logging, ...

Sometimes, we just want to list all the classes of a package in the system class loader. Let's see how we can do this.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset