12

我想在 Java 中实现一个基于注解的初始化机制。具体来说,我定义了一个注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Initialization {

/**
 * If the eager initialization flag is set to <code>true</code> then the
 * initialized class will be initialized the first time it is created.
 * Otherwise, it will be initialized the first time it is used.
 * 
 * @return <code>true</code> if the initialization method should be called
 *         eagerly
 */
boolean eager() default false;

}

另外,我有一个界面:

public interface SomeKindOfBasicInterface {}

我想SomeKindOfBasicInterface在我的类路径上找到该类的每个实现,该类在@Initialization方法上有注释。我正在查看 Spring 的MetaDataReader工具,这看起来像是在执行此操作时推迟加载其他实现的最佳方式SomeKindOfBasicInterface......但我不确定如何像我描述的那样进行搜索。有小费吗?

4

3 回答 3

10

您可以使用Reflections,这是一个 Java 运行时元数据分析工具。我用它来获取给定类型的所有子类型,但它也可以处理您的情况。

于 2009-03-22T22:20:05.043 回答
1

我基本上会创建一个BeanPostProcessor实现,可能基于CommonAnnotationBeanPostProcessor。然后我设置了组件扫描,它扫描类路径并选择所有符合您的规范的bean。初始化 bean 时,您的后处理器将运行。

我知道我假设您正在寻找豆类。如果不是这种情况,您可能必须自己扫描类路径。

于 2009-03-18T17:55:17.080 回答
1

您可以使用javassist查找类中的注释,甚至在加载它们之前,但您需要直接读取 .class 文件,这可能意味着您自己打开一个 JAR 等等。您还需要知道在哪里寻找类。您不能只向运行时询问BasicInterface.

于 2009-03-18T18:22:49.260 回答