本文介绍了是否可以获取类的所有子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我想获得一个在运行时用Java实现接口的类列表,这样我就可以进行查找服务无需硬编码。有一个简单的方法吗?我不担心。

I would like to get a list of classes that implement an interface in Java at runtime so I can do a lookup service without having to hard code it. Is there a simple way of doing this? I fear not.

推荐答案

答案很简短。

很长的答案是子类可以以多种方式存在,这基本上使得无法分类地找到它们。

The long answer is that subclasses can come into existence in many ways, which basically makes it impossible to categorically find them all.

你不能在运行时这样做但是你在加载之前找不到类,你怎么知道它们已被加载?您可以扫描每个JAR和类文件,但这不是确定的。还有像URL类加载器这样的东西。

You can't do it at runtime but you can't find classes until they're loaded and how do you know they're loaded? You could scan every JAR and class file but that's not definitive. Plus there are things like URL class loaders.

内部类(静态和非静态)是需要考虑的另一种情况。命名的内部类更容易找到。匿名内部类可能更难找到。

Inner classes (static and non-static) are another case to consider. Named inner classes are easier to find. Anonymous inner classes are potentially much more difficult to find.

你还必须考虑如果一个类有子类,那么可以在以后创建新的子类。

You also have to consider that if a class has subclasses then new subclasses can be created at a later point.

这篇关于是否可以获取类的所有子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 19:32