An annotation is a form of metadata added to the source code. They are used to inspect other code at programming level or change the behaviour of other classes at runtime.
Here is an example:
package uk.co.davisfiore; import java.lang.annotation.*; /** * This is an example of custom annotation that can be * applied to any methods * */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface MethodInfo { /** * Retrieve information about the method * * @return Type */ Type type() default Type.INTERNAL; } package uk.co.davisfiore; /** * Defines the type of method * */ public enum Type { /** * Indicates an external method */ EXTERNAL, /** * Indicates an internal method */ INTERNAL } package uk.co.davisfiore; /** * This class show how to use the annotation MethodInfo * */ class AnnotatedClass { /** * Example of method annotated with explicit parameter */ @MethodInfo(type = Type.EXTERNAL) public void explicitlyAnnotatedMethod() { } /** * Example of method annotated with default parameters */ @MethodInfo public void defaultAnnotatedMethod() { } /** * Example of non annotated method */ public void nonAnnotatedMethod() { } } package uk.co.davisfiore; import java.lang.reflect.Method; /** * This class show how to retrieve information from an annotated class * */ public class AnnotationTest { public static void main(String[] args) throws Exception { // Get all the methods from the annotated class Method[] methods = AnnotatedClass.class.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(MethodInfo.class)) { // Get the annotation info MethodInfo methodInfo = method.getAnnotation(MethodInfo.class); System.out.printf("Method: %s Type: %s\n", method.getName(), methodInfo.type()); } else { System.out.printf("Method: %s Annotation not present\n", method.getName()); } } } }
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.