Java Annotations Gotcha

by timvasil 1/27/2008 3:47:00 PM

I'm well accustomed to .NET attributes, so when I was recently writing some code using the Java equivalent, annotations, I was surprised to find the reflection methods I called were not providing me with the annotation metadata I had so painstakingly defined.

As it turns out, I was missing a @Retention attribute on the custom annotation interface I defined.  In order to access the annotation at runtime via reflection, I needed to say:

@Retention(RetentionPolicy.RUNTIME)

This is intuitive enough, just not something a .NET developer would expect to have to do, since in .NET attributes are always available at runtime via reflection.

So, the complete definition of the annotation interface I needed to slap on an enum value is:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ColumnName
{
    String columnName();
}

And reading the annotations on enum values, if present, is straightforward:

final Field[] fields = EnumType.class.getFields();
final String[] columnNames = new String[fields.length];
int idx = 0;
for (Field field : fields)
{
    final ColumnName columnNameAnn = field.getAnnotation(ColumnName.class);
    columnNames[idx++] = (columnNameAnn == null) ?
        ((Enum)field.get(null)).name() : columnNameAnn.columnName();
}

Tags:

Java

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading


Search

Calendar

«  May 2012  »
SuMoTuWeThFrSa
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

View posts in large calendar

Recent comments

Archive