Can you find all classes in a package using reflection?

前端 未结 27 2157
不知归路
不知归路 2020-11-21 05:24

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

27条回答
  •  情书的邮戳
    2020-11-21 05:50

    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> allClasses = 
         reflections.getSubTypesOf(Object.class);
    

提交回复
热议问题