JavaRanch Home
 
Front Page FAQs Ranchers Categories Recent Changes To Do Upload

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.reflect.Field;
import java.lang.reflect.Method;


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


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


@Retention( value=java.lang.annotation.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
Front Page FAQs Ranchers Categories Recent Changes To Do Upload
Last Edited: 29 September 2007 What's Changed?
 
Copyright © 1998-2008 Paul Wheaton | Home | Contact Us | Privacy | Register