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