JavaRanch Home    
 
This page:         last edited 10 July 2009         What's Changed?         Edit

Annotations Example   

This is a simple example of using annotations at runtime. Note the RetentionPolicy setting which determines whether or not an annotation can be retrieved by code at runtime. The code also demonstrates default values and annotations with more than one field.


import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
import java.lang.reflect.Method;


@Retention( value=RetentionPolicy.RUNTIME )
@interface FirstAnno
{
    String value() default "default";
}


@Retention( value=RetentionPolicy.RUNTIME )
@interface SecondAnno
{
    String someString();
    int someInt();
}


@Retention( value=RetentionPolicy.CLASS )
@interface ThirdAnno { }
/* this annotation will not show up at runtime */


@FirstAnno
@ThirdAnno
public class AnnotationTest
{
    @FirstAnno("not the default")
    public String whatever;

    @FirstAnno("yadda yadda")
    @SecondAnno(someString="yadda yadda", someInt=42)
    public void someMethod() { }

    public static void main (String argv[]) throws Exception
    {
        AnnotationTest at = new AnnotationTest();
        Class atClass = at.getClass();

        Annotation[] annotations = atClass.getAnnotations();
        for (Annotation anno : annotations)
            System.out.println("class : " + ((FirstAnno) anno).value());

        Field fld = atClass.getField("whatever");
        annotations = fld.getAnnotations();
        for (Annotation anno : annotations)
            System.out.println("method : " + ((FirstAnno) anno).value());

        Method mth = atClass.getMethod("someMethod");
        annotations = mth.getAnnotations();
        for (Annotation anno : annotations)
        {
            if (anno instanceof FirstAnno)
                System.out.println("field : " + ((FirstAnno) anno).value());
            else
                System.out.println("field : "
                        + ((SecondAnno) anno).someString() + "---" + ((SecondAnno) anno).someInt());
        }
    }
}


CategoryCodeSamples CodeBarn

JavaRanchContact us — Copyright © 1998-2013 Paul Wheaton