Java Reference
In-Depth Information
This is implemented in Example 23-19 .
Example 23-19. PluginsViaAnnotations::findAnnotatedClasses
/** Discover "plugins" or other add-in classes via Reflection using Annotations */
public
public class
class PluginsViaAnnotations
PluginsViaAnnotations {
/**
* Find all classes in the given package which have the given
* class-level annotation class.
*/
public
public static
static List < Class <?>> findAnnotatedClasses ( String packageName ,
Class <? extends
extends Annotation > annotationClass ) throws
throws Exception {
List < Class <?>> ret = new
new ArrayList <>();
String [] classes = ClassesInPackage . getPackageContent ( packageName );
for
for ( String clazz : classes ) {
Class <?> c = Class . forName ( clazz );
iif ( c . isAnnotationPresent ( annotationClass ))
ret . add ( c );
}
return
return ret ;
}
We can take this one step further, and support particular method annotations, similar to
javax.annotations.PostCreate , which is meant to decorate a method that is to be called
after an instance of the bean has been instantiated by the framework. Our flow is now
something like this, and the code is shown in Example 23-20 :
1. Get the list of classes in the given package(s) (again, see Listing Classes in a Pack-
age ) .
2. If you are using a class-level annotation, check if the class is annotated.
3. If this class is still of interest, get a list of its methods.
4. For each method, see if it contains a given method-specific annotation.
5. If so, add the class and method to a list of invocable methods.
Example 23-20. PluginsViaAnnotations::findAnnotatedMethods
/**
* Find all classes in the given package which have the given
* method-level annotation class on at least one method.
Search WWH ::




Custom Search