How can I find all classes on the classpath that have a specific method annotation?

淺唱寂寞╮ 提交于 2020-01-23 05:13:43

问题


I want to implement an intialization mechanism that is annotation-based in 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. 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. Any tips?


回答1:


You could use Reflections, which is a Java runtime metadata analysis tool. I've used it to get all subtypes of a given type, but it can handle your case as well.




回答2:


I would basically create a BeanPostProcessor implementation, maybe based on the CommonAnnotationBeanPostProcessor. Then I'd set up for component-scan that scans the classpath and picks up all the beans matching your specification. When the bean is initialized, your postprocessor will be run.

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.




回答3:


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. You can't just ask the runtime for all subclasses of your BasicInterface.



来源:https://stackoverflow.com/questions/659349/how-can-i-find-all-classes-on-the-classpath-that-have-a-specific-method-annotati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!