[英]How can I find all classes on the classpath that have a specific method annotation?
I want to implement an intialization mechanism that is annotation-based in Java.我想在 Java 中实现一个基于注解的初始化机制。 Specifically, I have an annotation I've defined:
具体来说,我定义了一个注释:
@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;
}
Additionally, I have an interface:另外,我有一个界面:
public interface SomeKindOfBasicInterface {}
I want to find every implementation of the SomeKindOfBasicInterface
class on my classpath that has the @Initialization
annotation on a method.我想在我的类路径上找到
SomeKindOfBasicInterface
class 的每个实现,该类路径在方法上有@Initialization
注释。 I'm looking at Spring's MetaDataReader
tools, which look like the best way to defer loading the other SomeKindOfBasicInterface
implementations while I'm doing this... but I'm not sure how to do a search like I'm describing.我正在查看 Spring 的
MetaDataReader
工具,它看起来是在我执行此操作时推迟加载其他SomeKindOfBasicInterface
实现的最佳方式......但我不确定如何进行我所描述的搜索。 Any tips?有小费吗?
You could use Reflections , which is a Java runtime metadata analysis tool.您可以使用Reflections ,这是一个 Java 运行时元数据分析工具。 I've used it to get all subtypes of a given type, but it can handle your case as well.
我用它来获取给定类型的所有子类型,但它也可以处理您的情况。
I would basically create a BeanPostProcessor implementation, maybe based on the CommonAnnotationBeanPostProcessor .我基本上会创建一个BeanPostProcessor实现,可能基于CommonAnnotationBeanPostProcessor 。 Then I'd set up for component-scan that scans the classpath and picks up all the beans matching your specification.
然后我设置了组件扫描,它扫描类路径并选择所有符合您的规范的 bean。 When the bean is initialized, your postprocessor will be run.
初始化 bean 时,您的后处理器将运行。
I see I am assuming that you're looking for beans.我知道我假设您正在寻找豆类。 If that's not the case you may have to scan the classpath yourself.
如果不是这种情况,您可能必须自己扫描类路径。
You can use javassist to find the annotations in your classes, even before you load them, but you need to read the.class files directly, which can mean opening a JAR by yourself, etc. Also you need to know where to look for the classes.您可以使用javassist在您的类中找到注释,甚至在加载它们之前,但您需要直接阅读 .class 文件,这可能意味着您自己打开 JAR 等。此外,您需要知道在哪里寻找类。 You can't just ask the runtime for all subclasses of your
BasicInterface
.您不能只向运行时询问
BasicInterface
的所有子类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.