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


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?




Is there something like asynchronous caching with ehcache and springmodules?

1:



Registering a shutdown hook in Spring 2.5
You could use Reflections, which is a Java runtime metadata analysis tool.


Spring Web Service Unit Tests: java.lang.IllegalStateExcepton: Failed to load Application Context
I've used it to get all subtypes of a given type, but it can handle your case as well..
Lingering Hibernate sessions without transaction in JBoss


Checking if specific user has a role


OSGi - How mature is this technology?

2:



Spring JDBC RowMapper with Class Hiearchies
I would basically create a BeanPostProcessor implementation, maybe based on the CommonAnnotationBeanPostProcessor.


Spring Webflow Best Practice
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..



85 out of 100 based on 85 user ratings 235 reviews