views:

557

answers:

3

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  A: 

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.

krosenvold
A: 

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.

Chochos
+2  A: 

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.

Kaitsu