Java Annotations Example
When I design and implement a new API, I always like to make the API easy to use. I was implementing a set of classes for usage in a Tree and a TreeTable. The only thing I wanted the user to implement is a class that defines the Node Data. For the Tree Table case I also needed information on getting the column count and whether the column was editable. My first implementation was to make it part of an interface
public interface ColumnData {
public void setData(int index, Object value);
public Object getData(int index);
public String[] getColumn(int index);
public boolean isEditable(int index);
}
The column list and whether it was editable was really static information for the class but I wanted to keep ColumnData as an interface instead of a class, so I created an annotation for defining the column information as show below
@Retention(RetentionPolicy.RUNTIME)
public @interface ColumnAttributes {
public String name();
public boolean editable() default false;
}
Below is an example of the how to use the annotations
@ColumnList(
columns = { @ColumnAttributes(name = "Name", editable = false), @ColumnAttributes ( name = "Salary", editable = true ) }
)
I then used reflection to read the annotations which is very straightforward
Object nodeData = nodeObj.getData();
for (Annotation an : nodeData.getClass().getAnnotations()) {
if (an instanceof ColumnList) {
ColumnList columnList = (ColumnList) an;
if (columnList.columns().length > column) {
b = columnList.columns()[column].editable();
return b;
}
}
}
public class MyData implements ColumnData {
}
Comments