Accessing every child class of parent class in Jav

2019-04-08 10:21发布

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??

3条回答
小情绪 Triste *
2楼-- · 2019-04-08 10:34

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.

查看更多
你好瞎i
3楼-- · 2019-04-08 10:50

You are correct: there is no direct API for this. I guess you could scan all loaded classes and see if they are a subclass of a given class.

One problem: you'll only able to find classes that are already loaded. None of these methods will find classes that haven't been loaded yet.

查看更多
你好瞎i
4楼-- · 2019-04-08 10:51

You can use:

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

I recently coded something to scan the members of a class and if those were non-primitives scan those as well. However, I did not traverse upwards so I didn't use the above methods but I believe they should do what you want.

EDIT: I ran 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's a matter of coding the traversal. If its parametrized then things may get a little complicated but still quite doable.

EDIT: Sorry didn't read carefully, let me look further into it.

EDIT: There doesn't seem to be any way to do it without scanning everything in your CLASSPATH and checking to make sure an object is an instance of some class.

查看更多
登录 后发表回答