Alex Rivera | Logout

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

Asked 2009-03-18T17:35:38.857
13

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?

Edit
Report

1 Answer

1

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.

answered 2009-03-18T18:22:49.260

Your Answer