If you use spring-context in your project: Here a working example to enumerate all types with the desired annotation:
/**
* Lists all types in the given package (recursive) which are annotated by the given annotation.
*
* All types which match the criteria are returned, no further checks (interface, abstract, embedded, etc.
* are performed.
*
*
* @param aAnnotation
* the desired annotation type
* @param aRoot
* the package name where to start the search.
* @return a list of found types
*/
private Collection extends Class>> findCandidatesByAnnotation( Class extends Annotation> aAnnotation,
String aRoot )
{
List> result = new ArrayList>();
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider( false )
{
@Override
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition)
{
return true;
}
};
scanner.addIncludeFilter( new AnnotationTypeFilter( aAnnotation ) );
Set canditates = scanner.findCandidateComponents( aRoot );
for ( BeanDefinition beanDefinition : canditates )
{
try
{
String classname = beanDefinition.getBeanClassName();
Class> clazz = Class.forName( classname );
result.add( clazz );
}
catch ( ClassNotFoundException t )
{
myLog.error( "Springs type scanner returns a class name whose class cannot be evaluated!!!", t );
}
}
return result;
}
This code was tested against spring-context-4.1.1.RELEASE under java 8.