简体   繁体   中英

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. 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?

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.

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM