Java Reflection - Get List of Packages

You can do this by using Package.getPackages(), which returns an array of all packages known to the current class loader. You'll have to manually loop through the array and find the ones with the appropriate prefix using getName().

Here's a quick example:

public List<String> findPackageNamesStartingWith(String prefix) {
    return Package.getPackages().stream()
        .map(Package::getName)
        .filter(n -> n.startsWith(prefix))
        .collect(toList());
}

Note that this technique will only return the packages defined in the current class loader. If you need the packages from a different class loader, there are some options:

  1. Arrange things so that your program can run the above code from inside that class loader. This requires a certain organisation to your code base, which may or may not be feasible.

  2. Use reflection to call the (normally protected) method getPackages() on the appropriate class loader. This won't work if the program is running under a security manager.