Archive for March, 2007

h1

Annotated Setters

March 27, 2007

Ever use reflection to derive the property name from a Method instance? It may end up looking something like this:

if (method.getName().startsWith("set")) {
    // derive property name
    String name = method.getName().substring(3);
    StringBuilder sb = new StringBuilder(name);
    sb.replace(0, 1, sb.substring(0, 1).toLowerCase());
    String property = sb.toString();
    // guard against false positives: e.g. setUp()
    // use a Set to filter duplicates
    Set fieldNames = new HashSet();
    Field[] fields = instance.getClass().getDeclaredFields();
    for (Field f : fields) {
        fieldNames.add(f.getName());
    }
    fields = instance.getClass().getFields();
    for (Field f : fields) {
        fieldNames.add(f.getName());
    }
    if (fieldNames.contains(property)) {
        // do stuff
    }
}

With Annotations, the job can be much simpler. Here’s the Annotation class:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Setter {
    public String forProperty();
}

Annotate a setter method and then it becomes a simple matter to see if the Method is a setter:

if (method.isAnnotationPresent(Setter.class)) {
    String property = method.getAnnotation(Setter.class).forProperty();
    // do stuff
}