English 中文(简体)
在Java中如何枚举超类的所有子类
原标题:How can I enumerate all child classes of a superclass in Java

我的应用程序由几个JAR文件组成。我想迭代所有JAR文件并找到所有子类特定类的类,以便我可以让它们的静态初始化器运行。

我查看了Java.lang.ClassLoader的Javadocs,但找不到任何方法可以做到这一点。

我正在尝试实现“产品交易者”设计模式(http://www.ubilab.com/publications/print_versions/pdf/plop-96-producttrader.pdf),使用在抽象超类中进行“自注册”的类。超类将具有一个HashMap,该HashMap将子类提供的服务和处理该服务的java.lang.Class文件进行映射。

问题是类不会运行它的静态初始化器直到它被加载。如果我可以迭代所有的子类,我可以强制每个子类加载并运行它的初始化器。

谢谢,拉尔夫

最佳回答

这通常是无法解决的。ClassLoader 不需要能够遍历它所加载的类。最简单的一个不能做到这一点的 ClassLoader 是从 http:// 基础 URL 加载类:HTTP 没有标准化的方法来枚举任何给定 URL 的内容。

一个更好的实现方法是使用ServiceLoader,并让所有实现类通过在其JAR文件中的简单条目注册自己。

问题回答

这显然不是很简单的问题。

然而,有解决方案,例如在这篇Javaworld文章中提到的

Generally speaking, it consists into exploration all elements from the CLASSPATH. if they re jar files, explore them looking for classes, load those classes and see if they extend you reference base class. However, i would strongly suggest you use a more "mature" mechanism like IoC or a plugin architecture.

我显然在考虑JSPF作为一个例子。

如果您真的需要这样做,唯一真正的方法是通过迭代类路径,在jar和目录中扫描类文件,加载该类并查看其父类。

注意,一些类会有静态初始化代码,可能会产生副作用,如从运行时加载X11类可能会长时间挂起。 如果可能,尽量将加载的类限制在特定的包中,例如 com.company(当然,您可以通过相对于类路径项根的类文件路径来识别包)。

[说明Joachim Sauer建议的服务贷款或提供类似机制的框架是一个更好的解决办法]





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签