[英]List Types of classes that inherit from another class
So, this is probably a simple question because I'm only missing a command here. 因此,这可能是一个简单的问题,因为我在这里仅缺少命令。 How can I list all the types of those classes that inherit from a specific class.
如何列出从特定类继承的那些类的所有类型。 Or formulated another way: How can I list the type of all child-classes from a class?
还是用另一种方式表达:如何列出一个班级中所有子班级的类型?
public class person {
person()
{
listChilds(this);
}
}
listChilds
in this case would produce a list that would probably contain classes like teacher
, footballPlayer
, student
, plumber
, etc. The getClass()
command of all the subclasses basically. 在这种情况下,
listChilds
会生成一个列表,该列表可能包含诸如teacher
, footballPlayer
, student
, plumber
等类。基本上所有子类的getClass()
命令。
Is there actually a way to do this? 实际上有办法吗?
It is impossible because a class does not know who inherits it. 这是不可能的,因为一个类不知道谁继承了它。 See oracle docs , here you can see the basic concept behind what you are trying to do.
请参阅oracle docs ,在这里您可以看到要执行的操作的基本概念。
While you cannot on-demand know of the classes that extend it, you can be slightly sneaky and cache anything that utilizes its constructor: 虽然您无法按需知道扩展它的类,但是您可能会有点偷偷摸摸并缓存任何利用其构造函数的东西:
public class Inheritance {
public Inheritance() {
System.out.println(this.getClass().getName());
}
public static void main(String[] args) {
Testing test = new Testing();
}
}
class Testing extends Inheritance {
public Testing() {
super();
}
}
Would print "Testing", using the this.getClass()
in the super constructor will return a Class<?>
instance of the class that is extending it. 将使用超级构造函数中的
this.getClass()
打印“测试”,将返回扩展它的类的Class<?>
实例。
It's rather easy with http://code.google.com/p/reflections/ . 使用http://code.google.com/p/reflections/相当容易。 This snippet lists all subclasses of
JPanel
, for example: 此代码段列出了
JPanel
所有子类,例如:
import java.util.Set;
import javax.swing.JPanel;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
public class SubtypesReflectionsTest
{
public static void main(String[] args)
{
Class<?> c = JPanel.class;
Reflections reflections = new Reflections(
"", ClasspathHelper.forClass(c),
new SubTypesScanner(false));
Set<?> subTypes = reflections.getSubTypesOf(c);
for (Object element : subTypes)
{
System.out.println("Class "+element);
}
}
}
But I agree with the comments: You should really think about what you are doing there, and if there is no more appropriate way to achieve your goal. 但是,我同意以下意见:您应该真正考虑自己在这里所做的事情,以及是否没有更合适的方法来实现自己的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.