Java 5: Annotation Example

Here’s an example of an annotation I’ve used. The software that runs this site represents content using a bunch of implementations of a basic Content inferface. Different types of content ? attachments, wiki pages, blog entries, etc. ? are represented by different persistent classes.

One of the problems that I wanted to solve, therefore, was relating to indexing the content for searching. I had a Spring interceptor that recognized when a piece of content needed to be saved, and it invoked the Lucene indexer. The only question was: what parts of the content needed to be indexed? Here’s where I used annotations.

First, I created an annotation that indicated which content properties needed to be indexed:

package ca.intelliware.ricardo.annotation;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

public @interface IndexProperty {
  String name();

Suppose I want to search for any content with the word “annotation” in the title, created some time in 2006. I’d use a Lucene query like this:

title:annotation date:[20060101 TO 20061231]

Obviously, I need to ensure that Lucene registers the stuff it’s indexing under the names “title” and “date”. Thus, I’d use the “name” value of the annotation to specify what name I’d use to index a particular content property.

Now I can have a content class like this:

public class WikiImpl implements Content {


  public String getTitle() {
    return this.title;


Now I have a snippet of code that introspects any content class as it’s being saved to the database. First, I do the usual introspection stuff to get a list of property descriptors of the class:

PropertyDescriptor[] descriptors = getPropertyDescriptors(content);
for (int i = 0, length = descriptors == null ? 0 : descriptors.length;
    i < length; i++) {

  IndexProperty indexProperty = getIndexProperty(descriptors[i]);
  if (indexProperty != null) {
    addFieldToLuceneDocument(descriptors[i], content,
        indexProperty, luceneDocument);

And the important piece is the getIndexProperty()method:

private IndexProperty getIndexProperty(PropertyDescriptor descriptor) {
  IndexProperty indexProperty = getIndexProperty(descriptor.getReadMethod());

  if (indexProperty == null) {
    indexProperty = getIndexProperty(descriptor.getWriteMethod());
  return indexProperty;

private IndexProperty getIndexProperty(Method method) {
  return method == null ? null : method.getAnnotation(IndexProperty.class);

This method looks for the annotation either on the read method, or the write method.

It's only fair to share...
Share on Facebook
Tweet about this on Twitter
Share on LinkedIn

Leave a Reply