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();
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Java

Related posts

Comments are closed

 

About the author

Tim Vasil Tim Vasil
I'm a software engineer living in Cambridge, MA.

E-mail me Send mail

Search

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Recent comments