We all love annotations. Really, they're nice markers for your pointcuts, create the option to have cross cutting concerns easily (i.e. only log these marked fields, or mask these annotated fields when logging).
However, we do need to be able to *get* to those annotations at runtime to inject those fancy tricks we have up our sleeve.
In comes the beautiful google reflections library which allows us to scan the class files for annotations.
Of course, we made those annotations available at runtime, right?
If not, add @Retention(RetentionPolicy.RUNTIME)to the annotation ;)
So, scanning at runtime done easy:
Collection<URL> urls = ClasspathHelper.forPackage("nl.shopname.location.domain");
Reflections reflections =
new Reflections(new ConfigurationBuilder().setUrls(urls).setScanners(new FieldAnnotationsScanner()));
Set<Field> fieldsWithAnnotation = <reflections.getFieldsAnnotatedWith(MyAnnotation.class);
And we're done. We can scan for fields, types, and then do cool things with them through the reflection if necessary. But that's a straightforward trick, maybe for a late post. Until then, use the library's javadoc.
Mind, in spring we can scan spring annotations with the spring scanner. This is a more generic variant...
However, we do need to be able to *get* to those annotations at runtime to inject those fancy tricks we have up our sleeve.
In comes the beautiful google reflections library which allows us to scan the class files for annotations.
Of course, we made those annotations available at runtime, right?
If not, add @Retention(RetentionPolicy.RUNTIME)to the annotation ;)
So, scanning at runtime done easy:
Collection<URL> urls = ClasspathHelper.forPackage("nl.shopname.location.domain");
Reflections reflections =
new Reflections(new ConfigurationBuilder().setUrls(urls).setScanners(new FieldAnnotationsScanner()));
Set<Field> fieldsWithAnnotation = <reflections.getFieldsAnnotatedWith(MyAnnotation.class);
And we're done. We can scan for fields, types, and then do cool things with them through the reflection if necessary. But that's a straightforward trick, maybe for a late post. Until then, use the library's javadoc.
Mind, in spring we can scan spring annotations with the spring scanner. This is a more generic variant...
Reacties
Een reactie posten