使用Java访问父类的每个子类 [英] Accessing every child class of parent class in Java

查看:111
本文介绍了使用Java访问父类的每个子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须实现一个给定子类的逻辑,我需要访问它的父类和该父类的所有其他子类(如果有的话)。我没有在Java Reflection中找到任何允许我们访问父类的所有子类的API。有什么方法可以吗?

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?

例如:

class B extends class A
class C extends class A

现在使用B类,我可以通过调用 getSuperClass()来查找超类。但有没有办法找到所有子类,一旦我有父类,即类B和类C ??

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

推荐答案

如果这不是家庭作业(可能不允许第三方图书馆),我建议 Google Reflections ' 思考#getSubTypesOf()

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);

您可以自己扫描类路径,从 ClassLoader# getResources() ,其中您传递作为名称。

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

这篇关于使用Java访问父类的每个子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆