Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection - Get List of Packages

I am building a Java app that has a number of different packages. I want to be able to tell programmatically which packages exist in the app that start with a specific pre-fix. Is there anyway to do this with the Java reflection APIs? I didn't see anything like this related to the reflection apis.

Example:

com.app.controls.text
com.app.controls.picker
com.app.controls.date
etc

I want to enumerate all of these by knowing the prefix "com.app.controls" and understanding that a new package might get integrated in the future.

Thanks!

like image 962
Derek Gebhard Avatar asked Dec 19 '12 02:12

Derek Gebhard


People also ask

What is Reflection in Java with example?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

How do I get all classes in a classpath?

You can get all classpath roots by passing an empty String into ClassLoader#getResources() . Enumeration<URL> roots = classLoader. getResources("");

How can you directly access all classes in the packages in Java?

1) Using packagename.* If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages. The import keyword is used to make the classes and interface of another package accessible to the current package.

How to get list of all packages in Java?

You can do this by using Package. getPackages(), which returns an array of all packages known to the current class loader.


1 Answers

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.

like image 148
Sean Reilly Avatar answered Oct 03 '22 02:10

Sean Reilly