Access to each child class of the parent class in Java

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

For instance:

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 a way to find all child classes when I have a parent class, i.e. class B and class C ??

+4
source share
3 answers

If it weren’t homework (where third-party libraries might not be allowed), I would suggest Google Reflections ' Reflections#getSubTypesOf() .

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

You can do this less or more yourself by scanning the class path yourself, starting with ClassLoader#getResources() , in which you pass "" as a name.

+11
source

You are right: there is no direct API for this. I think you can scan all loaded classes and see if they are a subclass of this class.

One problem: you can only find classes that are already loaded. None of these methods will find classes that are not yet loaded.

+5
source

You can use:

 thisObj.getClass().getSuperclass() thisObj.getClass().getInterfaces() thisObj.getClass().getGenericInterfaces() thisObj.getClass().getGenericSuperclass() 

I recently coded something to scan class elements, and if they were non-primitive, scan them as well. However, I did not go up, so I did not use the above methods, but I believe that they should do what you want.

EDIT: I checked a simple test with the following:

 public class CheckMe { public CheckMe() { } } public class CheckMeToo extends CheckMe { public CheckMeToo() { } } // In main System.out.println( CheckMeToo.class.getSuperclass() ); // Output class CheckMe 

After that, it is a workaround coding issue. If you parameterize it, then everything can become a little complicated, but still quite feasible.

EDIT: Sorry, did not read carefully, let me look further.

EDIT: There seems to be no way to do this without looking at everything in your CLASSPATH and checking that the object is an instance of some class.

-1
source

Source: https://habr.com/ru/post/1307745/


All Articles