Alotor Alotor - 1 year ago 124
Java Question

Scanning Java annotations at runtime

What is the best way of searching the whole classpath for an annotated class?

I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation.

Do you know a library or a Java facility to do this?

Edit: I'm thinking about something like the new functionality for Java EE 5 Web Services or EJB's. You annotate your class with

and the system finds these classes while loading so they are accessible remotely.

Answer Source

Use org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider


A component provider that scans the classpath from a base package. It then applies exclude and include filters to the resulting classes to find candidates.

ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFALT_FILTER>);

scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));

for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download