My first use of an Annotation

I made use of an Annotation for the first time today, and it was a very pleasant experience!

I have a number of classes which all extend the same abstract class. These classes have a number of public getter methods, and some of the getter methods are used to retrieve values which I want to display in a GUI. The problem was how I should distinguish between these and the other getter methods.

First I thought I'd use reflection, but then I'd have to name my printable getters in a similar way, which didn't feel right.

So I thought I would check out that new thing called annotations, and it fit the bill perfectly! I could even add a field to deal with the order they should be sorted.

I started by creating my annotation like this:

package example;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Printable {
    String displayName() default "";
    int sortOrder() default 0; // sort the items in ascending order
}

Now I can annotate all methods in my sub-class which I want print:

public class SubClass extends AbstractClass {
    @Printable(displayName = "Execute command", sortOrder = 1)
    public String getCmd() {
        return this.cmd;
    }
}

And finally I can the the following code snippet to print subClass. Note that I've skipped the sorting.

public void classPrinter(AbstractClass c) {
    for (Method m:c.getClass().getMethods()) {
        if (m.isAnnotationPresent(Printable.class)) {
            Printable p = m.getAnnotation(Printable.class);
            String displayName = p.displayName();
            System.out.println("displayName = " + displayName);
            int i = p.sortOrder();
            System.out.println("sortOrder = " + i);
            String result = m.invoke(c, (Object[]) null); // get value
            System.err.println("result = " + result);
        }
    }
}

[Technorati Tags: ]

Comments:

Post a Comment:
Comments are closed for this entry.
About

martin

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today