1

Using Java reflection API only (java.lang.reflect package ), can we determine child (surbordinate) classes in a class hierarchy?

Hiru
  • 11
  • 4
  • 1
    I don't think so, this information cannot be known without parsing the classpath. – Arnaud Denoyelle Jun 15 '17 at 08:13
  • this might give you a clue https://stackoverflow.com/questions/205573/at-runtime-find-all-classes-in-a-java-application-that-extend-a-base-class – Shafin Mahmud Jun 15 '17 at 08:24
  • 2
    You have to make a distinction between “all loaded subclasses” and “all potential subclasses”. Of course, a JVM knows all loaded classes, but questions like this are usually heading at the potential classes, but this is an infinite amount, as this would include classes which someone could create *after* the query, to be added to the environment dynamically. – Holger Jun 15 '17 at 10:27
  • @Holger Whatever the java equivalent of the CLR `for (Assembly a : appDomain.currentDomain.getAssemblies()) { for (Type t : a.getTypes()) { ... } }` is. .NET is able to find classes at runtime, even ones that haven't been created yet. So Java must be able to do it too. – Ian Boyd Jul 21 '22 at 20:07
  • 1
    @IanBoyd first, you would need the equivalent to an Assembly, which a classpath/classloader based Java environment doesn’t have. The closest equivalent would be a Module, if you chose to use the module system actively. Then, you can iterate the classes statically defined in that module. But it’s still possible to add classes dynamically at runtime, e.g. using [`defineClass(…)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/invoke/MethodHandles.Lookup.html#defineClass(byte%5B%5D)). You can’t predict beforehand, which classes will be created that way. – Holger Jul 22 '22 at 09:11

0 Answers0