How do you find all subclasses of a given class in Java?

How does one go about and try to find all subclasses of a given class (or all implementors of a given interface) in Java? As of now, I have a method to do this, but I find it quite inefficient (to say the least). The method is:

  • Get a list of all class names that exist on the class path
  • Load each class and test to see if it is a subclass or implementor of the desired class or interface
  • In Eclipse, there is a nice feature called the Type Hierarchy that manages to show this quite efficiently. How does one go about and do it programmatically?


    There is no other way to do it other than what you described. Think about it - how can anyone know what classes extend ClassX without scanning each class on the classpath?

    Eclipse can only tell you about the super and subclasses in what seems to be an "efficient" amount of time because it already has all of the type data loaded at the point where you press the "Display in Type Hierarchy" button (since it is constantly compiling your classes, knows about everything on the classpath, etc).


    Scanning for classes is not easy with pure Java.

    The spring framework offers a class called ClassPathScanningCandidateComponentProvider that can do what you need. The following example would find all subclasses of MyClass in the package org.example.package

    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AssignableTypeFilter(MyClass.class));
    
    // scan in org.example.package
    Set<BeanDefinition> components = provider.findCandidateComponents("org/example/package");
    for (BeanDefinition component : components)
    {
        Class cls = Class.forName(component.getBeanClassName());
        // use class cls found
    }
    

    This method has the additional benefit of using a bytecode analyzer to find the candidates which means it will not load all classes it scans.


    This is not possible to do using only the built-in Java Reflections API.

    A project exists that does the necessary scanning and indexing of your classpath so you can get access this information...

    Reflections

    A Java runtime metadata analysis, in the spirit of Scannotations

    Reflections scans your classpath, indexes the metadata, allows you to query it on runtime and may save and collect that information for many modules within your project.

    Using Reflections you can query your metadata for:

  • get all subtypes of some type
  • get all types annotated with some annotation
  • get all types annotated with some annotation, including annotation parameters matching
  • get all methods annotated with some
  • (disclaimer: I have not used it, but the project's description seems to be an exact fit for your needs.)

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

    上一篇: Java中的接口命名

    下一篇: 你如何找到Java中给定类的所有子类?