import java.lang.reflect.*; import java.lang.annotation.*; // The Annotation Type @Retention(RetentionPolicy.RUNTIME) @interface SayHi { public String value(); } // The Annotated Class @SayHi("Hello, class!") class HelloWorld { @SayHi("Hello, field!") public String greetingState; @SayHi("Hello, constructor!") public HelloWorld() { } @SayHi("Hello, method!") public void greetings() { } } // The Annotation Consumer public class HelloWorldAnnotationTest { public static void main( String[] args ) throws Exception { //access the class annotation Class clazz = HelloWorld.class; System.out.println( clazz.getAnnotation( SayHi.class ) ); //access the constructor annotation Constructor constructor = clazz.getConstructor((Class[]) null); System.out.println( constructor.getAnnotation(SayHi.class)); //access the method annotation Method method = clazz.getMethod("greetings"); System.out.println(method.getAnnotation(SayHi.class)); //access the field annotation Field field = clazz.getField("greetingState"); System.out.println(field.getAnnotation(SayHi.class)); } }