Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing every child class of parent class in Java

I have to implement a logic whereby given a child class, I need to access its parent class and all other child class of that parent class, if any. I did not find any API in Java Reflection which allows us to access all child classes of a parent class. Is there any way to do it?

For example:

class B extends class A
class C extends class A

Now using class B, I can find the superclass by calling getSuperClass(). But is there any way to find all the child classes once I have the parent class i.e. class B and class C??

like image 278
name_masked Avatar asked Apr 23 '10 00:04

name_masked


1 Answers

If this wasn't homework (where 3rd party librares are probably not allowed), I would have suggested Google Reflections' Reflections#getSubTypesOf().

Set<Class<? extends A>> subTypes = reflections.getSubTypesOf(A.class);

You can do this less or more yourself by scanning the classpath yourself, starting with ClassLoader#getResources() wherein you pass "" as name.

like image 134
BalusC Avatar answered Sep 25 '22 00:09

BalusC