customannotation

Custom Java annotations – Quick example of easy and powerful Java function

Development of custom Java annotations is really quick and usage of annotations is really awesome and it provides very easy way how to offer customization. In this short post we are going to create a simple application with custom annotation for FIELD type. I’d like to show you only basic concept and I believe that change of this example to other types of annotation will be easy for you.

How to create annotation class?

Let’s start with definition – public @interface NAME {}

Also we need to say where this annotation should be expected, it means which type of annotation it is? For this example, we are going to create an annotation for fields (for others types and descriptions see Java doc of ElementType) and also we’d like to be able to access to this metadata during runtime of application. For this Java offers RetentionPolicy (Java doc of RetentionPolicy).

If you are going to use your annotation as part of public API, don’t forget to add @Documented annotation into your custom annotation class. From JavaDoc: Indicates that annotations with a type are to be documented by javadoc and similar tools by default.

So now our custom annotation FieldInfo.class looks like this:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface FieldInfo {

}

Now we can create some metadata like name and value for annotated fields. Name is required string parameter for our FieldInfo.class and value is optional integer parameter. When we’d like to set parameter optional, we need to define a default value (here we are going to get 21 as default value). And that’s all, we finished our first custom annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface FieldInfo {
  String name();
  int value() default 21;
}

 How to work with annotations?

Here is simple usage of our annotation:

import java.lang.reflect.Field;
import org.hrabosch.example.annotation.FieldInfo;

public class Main {

  @FieldInfo(name = "My first object")
  Object holder = new Object();

  Object holderWithoutAnnotation = new Object();

  @FieldInfo(name = "Age", value = 35)
  Integer ageHolder = new Integer(0);

    public static void main(String[] args) throws NoSuchFieldException {

    	for (Field field : Main.class.getDeclaredFields()) {
    		if (field.isAnnotationPresent(FieldInfo.class)) {
    			FieldInfo info = field.getAnnotation(FieldInfo.class);
          System.out.println("Field: " + field.getName());
          System.out.println("-- Name defined by annotation: " + info.name());
          System.out.println("-- Value defined by annotation: " + info.value());
        }
      }

    }
}

Result:

Field: holder
-- Name defined by annotation: My first object
-- Value defined by annotation: 21
Field: ageHolder
-- Name defined by annotation: Age
-- Value defined by annotation: 35

Process finished with exit code 0

Whole point is always in reflection and two methods: isAnnotationPresent(Class<? extends Annotation> annotationClass)

and getAnnotation(Class<T> annotationClass).

Aleš Laňar
Senior Engineer Software ve společnosti CA Technologies

Leave a Reply

Your email address will not be published. Required fields are marked *