如何在类路径中找到具有特定方法注释的所有类?

Chr*_*s R 10 java spring annotations

我想在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;

}
Run Code Online (Sandbox Code Playgroud)

另外,我有一个界面:

public interface SomeKindOfBasicInterface {}
Run Code Online (Sandbox Code Playgroud)

我想SomeKindOfBasicInterface在我的类路径上找到类的每个实现,它@Initialization在方法上有注释.我正在看Spring的MetaDataReader工具,这看起来是推迟加载其他SomeKindOfBasicInterface实现的最佳方式,而我正在这样做......但我不知道如何像我所描述的那样进行搜索.有小费吗?

Kai*_*tsu 10

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

  • 如果时间/空间效率远远受到关注,我强烈建议不要使用反射或基本上使用类加载器.你的类路径中可能有很多类,所有这些加载的类现在都在permgen中.使用类似ASM(或字节码库)的东西,只需读取byte [],使用ASM库获取有关类的信息,例如'是否用x注释?' 然后才实际加载该类(如果你碰巧需要那个类). (6认同)