如何在类路径中找到具有特定方法注释的所有类?
我想在Java中实现一个基于注释的初始化机制。 具体来说,我有一个我定义的注释:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Initialization { /** * If the eager initialization flag is set to true
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 true
if the initialization method should be called * eagerly */ boolean eager() default false; }
另外,我有一个界面:
public interface SomeKindOfBasicInterface {}
我想在我的类路径上找到SomeKindOfBasicInterface
类的每个实现,该类在方法上具有@Initialization
注释。 我正在看Spring的MetaDataReader
工具,这看起来是推迟加载其他SomeKindOfBasicInterface
实现的最佳方式,而我正在这样做…但我不知道如何进行搜索,就像我在描述的那样。 有小费吗?
您可以使用Reflections ,它是一个Java运行时元数据分析工具。 我用它来获取给定类型的所有子类型,但它也可以处理你的情况。
我基本上会创建一个BeanPostProcessor实现,可能基于CommonAnnotationBeanPostProcessor 。 然后我设置了组件扫描 ,它扫描类路径并获取符合您规范的所有bean。 初始化bean时,将运行后处理器。
我看到我假设你正在寻找豆子。 如果不是这种情况,您可能需要自己扫描类路径。
您甚至可以在加载之前使用javassist查找类中的注释,但是您需要直接读取.class文件,这可能意味着您自己打开JAR等。此外,您需要知道在哪里查找类。 您不能只询问运行时BasicInterface
所有子类。