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.