6

Possible Duplicate:
At runtime, find all classes in a Java application that extend a base class

I need to get list of all the classes (child) which extends a particular class (parent) and then create an instance of them all.

how should I do this in Java?

Community
  • 1
  • 1
MBZ
  • 26,084
  • 47
  • 114
  • 191
  • Please have a look at http://stackoverflow.com/questions/205573/at-runtime-find-all-classes-in-a-java-application-that-extend-a-base-class – Chetter Hummin Apr 23 '12 at 08:04
  • I assume that there are some constraints, for example a set of packages. It is impossible to find every classes that extend a certain class without any constraint given. – Jagger Apr 23 '12 at 08:05

1 Answers1

6

I would use http://code.google.com/p/reflections/

Using Reflections you can query your metadata such as:

  • get all subtypes of some type
  • get all types/methods/fields annotated with some annotation, w/o annotation parameters matching
  • get all resources matching matching a regular expression

This can be used in an indexed or cached mode. As @Jagger suggests, a brute force search of every class is relatively slow. You can also limit the search by package e.g. com.mycom.*

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • I doubt you'll be able to use the reflections API for finding all the classes which extend a given class. I might be wrong though. I.e. You can easily use the reflections API to get the supertypes of some type, but not to get all possible subtypes of a type. – Alderath Apr 23 '12 at 08:08
  • 1
    This is what the library does. Not to be confused with [The Reflection API](http://docs.oracle.com/javase/tutorial/reflect/index.html) which as you say doesn't do this. ;) – Peter Lawrey Apr 23 '12 at 08:12
  • 1
    My mistake. Disregard my previous comment. I focused mainly on reading the grey box and assumed you meant java.lang.reflect. – Alderath Apr 23 '12 at 08:16