Java 5 Annotations – Creating your own Annotation Type

2

One of the new features in Java 5 that clearly stands out is called: Annotations (JSR-175). Through Annotations, we can add metadata to our Java sources, not just as custom tags in JavaDoc comments – as we used to do with simple annotations such as @author or @deprecated or more advanced annotations used by XDoclet or AspectJ – but as constructs that are supported by IDEs and checked by compilers. In a recent workshop in session of our Web & Java Knowledge Center, we implemented a very simple AnnotationType, called Descriptor Annotation, that had a direct impact on the toString() method. In a few simple steps, we define the Annotation Type, use it to annotate a class and write the runtime code to leverage the annotation, through Reflection. This article illustrates this process.

....
Annotations have a much longer history than Java 5. They have been abundantly used in C# to specify meta-data in code. In Java, tools like XDoclet, Apache Commons, MetaClass, qDox, JAM and others have used special tags inside JavaDoc comments as annotations. Runtime annotations could be achieved in somewhat farfetched way by using Marker Interfaces or even implementing dummy methods. In Java 5, such tricks are no longer necessary as Annotations are now part of the core Java Programming Language.
 
Given the history, it seems logical that the first serious usages of Annotations can be found in tools and frameworks that tried JavaDoc style tags before Java 5. Recent releases of AspectJ (5) and JUnit (4.0) as well as the Spring Framework, XFire, Tapesttry and many others are leveraging the Annotations concept. Additionally, some very important JEE 5 specifications involve or revolve around Annotations; most notably are JSR-220 EJB 3.0 Persistence and JSR-181 WebServices Meta-Data.

Some of the Java 5 Annotations objectives:

  • Declaratively specify meta-data (Without the need for external XML files)
  • Compile time verification – No typo’s, upper/lower case mismatch
  • Code completion in IDEs (Facilitate IDE support)
  • Provide meta-data access at Source file level/Compile time,Class Load Time, Run Time – extension of reflection API

There are a few things we can say in general about annotations and their appearance:

Annotations are included in the source code, just before the target they apply to. An annotation is included using the @ character, followed by the name of the Annotation Type. For example: @Entity or @Table(name="MY_TABLE"). Between parentheses, we can supply values for parameters of our annotation. Note that the parameters can be of complex types. For example:

 

@ManyToMany(cascade=CascadeType.ALL)<br />    @JoinTable(table = @Table(name = &quot;als_authorships&quot;), joinColumns = {<br />           @JoinColumn(name = &quot;bok_id&quot;)<br />       }, inverseJoinColumns = {<br />           @JoinColumn(name = &quot;atr_id&quot;)<br />       })<br />    public Collection&lt;Author&gt; getAuthors() {<br />        return this.authors;<br />    }

The AnnotationType must be imported, like a Class or Interface definition. Annotation Types must be on the project’s build path as well as – for runtime annotations – the classpath. An Annotation is part of the code, it is not in comments. Annotation is located just before its target. Potential targets are: Package, Class, Field, Constructor, Method, Parameter, Local Variable,
Annotation. Yes, an Annotation (type) can be annotated as well. We will see an example of such a meta-annotation in a short while.

Retention Policy

Annotations can live in different worlds. Part of the definition of the Annotation (Type) is an indication of its retention policy. Three levels can be set:

  • Source- Annotation is only in the source file. Can be used by a preprocessor at compile-time
  • Class (default) – Annotation is in the classfile, but cannot be accessed at runtime. Useful for postprocessors that work directly on the classfile
  • Runtime – Annotation is in the classfile and can be accessed via the introspection APIs

Creating our own Annotation Type

As developers, we will not create new annotation types all the time. Using the annotation types specified or required by frameworks like AspectJ 5, JUnit, EJB 3.0 Psersistence will be a much more frequent task. However, it is interesting to know how to create an annotation type, and you may find good uses for your own annotation types all the same.

In this example, we will create an Annotation called Descriptor. It can be used to mark the getter methods in our class that participate in completely describing instances of our class. For example the getters getId and getName are both annotated with the @Descriptor annotation in our Product Class, indicating that a description of Product objects that humans can understand can be constructed from those two setters. Or the class Person has getFirstName, getLastName and getBirthdate annotated with @Descriptor. We will later see how we can make use of these annotations at run time.

First our annotation with its attributes:

package nl.amis.annotation.descriptor;<br /><br />import java.lang.annotation.ElementType;<br />import java.lang.annotation.Retention;<br />import java.lang.annotation.RetentionPolicy;<br />import java.lang.annotation.Target;<br /><br />@Retention(RetentionPolicy.RUNTIME)<br />@Target(ElementType.METHOD)<br />public @interface Descriptor {<br />    int sequence() default 1;<br />    String label() default &quot;&quot;;<br />    String value() default &quot;&quot;;<br />}<br />&nbsp;

The attribute sequence specified the position of the getter-method within the display label. The label attribute is used to specify the prompt that can be included in the displaylabel.

Next we will use the Annotation in the Employee Class. We assume that FirstName, LastName and Job together and in this order provide a meaningful description for Employees. So we have annotated the associated getter-methods:

package nl.amis.hrm;<br /><br />import nl.amis.annotation.descriptor.Descriptor;<br />import nl.amis.annotation.AnnotatedObject;<br /><br />public class Employee {<br />        private Double commission;<br />        private Long empno;<br />        private String firstName;<br />        private String lastName;<br />        private String job;<br />        private Double salalary;<br />      <br />        public Employee() {<br />        }<br /><br />    public void setCommission(Double commission) {<br />        this.commission = commission;<br />    }<br /><br />    public Double getCommission() {<br />        return commission;<br />    }<br /><br />    public void setEmpno(Long empno) {<br />        this.empno = empno;<br />    }<br /><br />    public Long getEmpno() {<br />        return empno;<br />    }<br /><br />    @Descriptor(label=&quot;First Name&quot;,sequence=1)<br />    public void setFirstName(String firstName) {<br />        this.firstName = firstName;<br />    }<br /><br />    public String getFirstName() {<br />        return firstName;<br />    }<br /><br />    public void setLastName(String lastName) {<br />        this.lastName = lastName;<br />    }<br /><br />    @Descriptor(label=&quot;Last Name&quot;,sequence=2)<br />    public String getLastName() {<br />        return lastName;<br />    }<br /><br />    public void setJob(String job) {<br />        this.job = job;<br />    }<br /><br />    @Descriptor(label=&quot;Job&quot;,sequence=3)<br />    public String getJob() {<br />        return job;<br />    }<br /><br />    public void setSalalary(Double salalary) {<br />        this.salalary = salalary;<br />    }<br /><br />    public Double getSalalary() {<br />        return salalary;<br />    }<br />}<br />&nbsp;

Now we have HrmManager cla
ss with a main method that i
nstantiates new Employee, assigns values through its setters and then displays its displaylabel to the console:

package nl.amis.hrm;<br /><br />public class HrmManager {<br />    public HrmManager() {<br />    }<br /><br />    public static void main(String[] args) {<br />        HrmManager hrmManager = new HrmManager();<br />        Employee scott = new Employee();<br />        scott.setFirstName(&quot;Harry&quot;);<br />        scott.setLastName(&quot;Scott&quot;);<br />        scott.setJob(&quot;Developer&quot;);<br />        scott.setSalalary(new Double(&quot;32421&quot;));<br />        <br />        System.out.println(scott);<br />    }<br />}<br /><br />

If we run this manager, we see no meaningful output whatsoever. Have our @Descriptor annotations failed somehow?

nl.amis.hrm.Employee@4<br /> <br />

The point is: we have not made use of the annotations anywhere. We have included them in the Employee class and since they were defined with Runtime Retention Policy they are available in the Employee Class at runtime, accessible through the Reflection API. But if we do not ask for it, they will not do anything by themselves.

In the class AnnotatedObject that extends Object, we have overridden the default toString() method. In our toString(), we get a list of all methods in the class, iterate over them and checks for each one of them if they have been annotated by @Descriptor. If so, the method is invoked and the result is added to the display label:

package nl.amis.annotation;<br /><br />import java.lang.reflect.InvocationTargetException;<br />import java.lang.reflect.Method;<br />import java.util.Iterator;<br />import java.util.SortedMap;<br />import java.util.TreeMap;<br />import nl.amis.annotation.descriptor.Descriptor;<br /><br />public class AnnotatedObject {<br /><br />    public String toString() {<br />        String tostring = &quot;&quot;;<br />        Method[] methods = this.getClass().getDeclaredMethods();<br />        SortedMap descriptors = new TreeMap();<br />        for (Method m: methods) {<br />            Descriptor annotation = m.getAnnotation(Descriptor.class);<br />            if (annotation == null) {<br />                continue;<br />            }<br />            Object[] args = null;<br />            try {<br />                descriptors.put(new Integer(annotation.sequence())<br />                    , annotation.label() + &quot; &quot; + m.invoke(this, args));<br />            } catch (InvocationTargetException ite) {<br />            } catch (IllegalAccessException iae) {<br />            }<br />        }<br />        // if no annotated methods were found, fall back on the default toString implementation<br />        if (descriptors.isEmpty()) {<br />            tostring = super.toString();<br />        } else {<br />            Iterator&lt;String&gt; descriptorIterator = <br />                descriptors.values().iterator();<br />            while (descriptorIterator.hasNext()) {<br />                tostring = tostring + &quot;;&quot; + descriptorIterator.next();<br />            }<br />        }<br />        return tostring.substring(1);<br />    }<br /><br />}<br /><br />

Now we have Employee extend AnnotatedObject:

package nl.amis.hrm;<br /><br />import nl.amis.annotation.descriptor.Descriptor;<br />import nl.amis.annotation.AnnotatedObject;<br /><br />public class Employee extends AnnotatedObject {<br />        private Double commission;<br />... <br />

And run HrmManager again:

First Name Harry;Last Name Scott;Job Developer<br />&nbsp;

If we change the annotations in Employee, removing @Descriptor from getFirstName and adding it to getSalary, the outcome is as follows:

Last Name Scott;Job Developer;Salary 32421.0<br />&nbsp;

Here we have seen a simple example of creating and using your own Annotation. It should help you create Annotations of your own.

Resources

Download the sources for the AnnotationsWorkshop: to be added later

Share.

About Author

Lucas Jellema, active in IT (and with Oracle) since 1994. Oracle ACE Director for Fusion Middleware. Consultant, trainer and instructor on diverse areas including Oracle Database (SQL & PLSQL), Service Oriented Architecture, BPM, ADF, Java in various shapes and forms and many other things. Author of the Oracle Press book: Oracle SOA Suite 11g Handbook. Frequent presenter on conferences such as JavaOne, Oracle OpenWorld, ODTUG Kaleidoscope, Devoxx and OBUG. Presenter for Oracle University Celebrity specials.

2 Comments

  1. The article looked at first like a good one, but then the code samples totally killed it, as their formatting is terribly *’d up. Have you considered plugging syntax highlighter into your web site? It’s not that difficult to set up and will make reading your blog so much easier.

  2. Good Article.  In this particular example, @Descriptor annotation should be used in getters rather than on setters.
    Thanks