Can you find all classes in a package using reflection?

Is it possible to find all classes or interfaces in a given package? (Quickly looking at eg Package , it would seem like no.)


Due to the dynamic nature of class loaders, this is not possible. Class loaders are not required to tell the VM which classes it can provide, instead they are just handed requests for classes, and have to return a class or throw an exception.

However, if you write your own class loaders, or examine the classpaths and it's jars, it's possible to find this information. This will be via filesystem operations though, and not reflection. There might even be libraries that can help you do this.

If there are classes that get generated, or delivered remotely, you will not be able to discover those classes.

The normal method is instead to somewhere register the classes you need access to in a file, or reference them in a different class. Or just use convention when it comes to naming.

Addendum: The Reflections Library will allow you to look up classes in the current classpath. It can be used to get all classes in a package:

 Reflections reflections = new Reflections("my.project.prefix");

 Set<Class<? extends Object>> allClasses = 
     reflections.getSubTypesOf(Object.class);

You should probably take a look at the open source Reflections library. With it you can easily achieve what you want.

First, setup the reflections index (it's a bit messy since searching for all classes is disabled by default):

List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();
classLoadersList.add(ClasspathHelper.contextClassLoader());
classLoadersList.add(ClasspathHelper.staticClassLoader());

Reflections reflections = new Reflections(new ConfigurationBuilder()
    .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
    .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
    .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("org.your.package"))));

Then you can query for all objects in a given package:

Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);

Google Guava 14 includes a new class ClassPath with three methods to scan for top level classes:

  • getTopLevelClasses()
  • getTopLevelClasses(String packageName)
  • getTopLevelClassesRecursive(String packageName)
  • See the ClassPath javadocs for more info.

    链接地址: http://www.djcxy.com/p/84172.html

    上一篇: 您在Java项目中使用什么策略进行软件包命名?为什么?

    下一篇: 你可以使用反射来查找包中的所有类吗?