Originally posted on: http://geekswithblogs.net/JoshReuben/archive/2015/03/20/java-annotations-refresher.aspx
Annotations (Metadata)
embed metadatain source code, for design-time/compile-time/run-time processing
Syntax -@<annotation-name>(<member initializations>)
the bedrock of JEE
AnnotationDefinition
Importjava.lang.annotationpackage
@interface-indicates an annotation type
annotation types automatically extend Annotation interface - specifies annotationType() - returns aClass object representing the invoking annotation.
use an annotation to annotate a declaration (classes, methods, fields, parameters, enum constants).
@Retention(RetentionPolicy) - specifywhen an annotation is discarded. java.lang.annotation.RetentionPolicy enum values:.
SOURCE - retained only in source file - discarded in compilation
CLASS - stored in .class file during compilation – discarded by JVM during run time.
RUNTIME - stored in .class file during compilation + available through JVM during run time.
Note: annotations on local variablesare not retained.
@Documented - marker to inform tool that an annotation is to be documented.
@Target - specifies types of declarations to which an annotation can be applied – specified byElementType enumeration: ANNOTATION_TYPE, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE
@Target( { ElementType.METHOD, ElementType.LOCAL_VARIABLE } )
@Inherited– for class annotations, causes the annotation for a superclass to be inherited by a subclas.
annotation member default values - adddefault clause to a member’s declaration – value does not need to be specified when annotation is applied
@Retention(RetentionPolicy.RUNTIME)@interface MyAnnotation { String s() default "blah";...@MyAnnotation()public void myMethod() {
Marker annotations - contain no members, its presence as an annotation is sufficient – can leave off paranthesis on application
Single-memberannotations -contain only one member. can simply specify the value for that member — don’t need to specify its name , which must be value.
@Retention(RetentionPolicy.RUNTIME)@interface MyAnnotation { int value(); // this variable name must be value}...@MyAnnotation(111)public void myMethod() {
can use the single-value syntax when applying an annotation that has other members, but those other members must all have default values.
Definition Restrictions
annotation cannot inherit from other annotations, and cannot be generic.
Members - all methods declared by an annotation must be without parameters andmust return one of the following: A primitive type, String , Class, anenum type, another annotation type, or an array of one of the preceding types.
Annotation methods cannot specify a throws clause.
Runtime Usage
Importjava.lang.reflect package
Obtainannotations(with a retention policy of RUNTIME)atrun-timeviareflection
getClass( ) -obtain a Class object
Class<?> - exposes reflection methods:getMethod( ),getField( ),getConstructor( ) return objects of type Method,Field,Constructor.These objects exposegetAnnotation() - obtain specific annotation associated with that object
The AnnotatedElement InterfaceMethods:getAnnotation(),getAnnotations()getDeclaredAnnotations(),isAnnotationPresent( )
getAnnotations( ) - obtain an array ofall annotations (that have RUNTIME retention) that are associated with a reflectionobject
eg
import java.lang.annotation.*;import java.lang.reflect.*;// definition@Retention(RetentionPolicy.RUNTIME)@interface MyAnnotation { String s(); int i();}...// applicationclass MyClass { @MyAnnotation(s = "blah", i = 1) public static void myMethod(String s, int i){}}...// reflectionMyClass obj = new MyClass();try { Class<?> c = obj.getClass(); // param types for method signature must be specified: Method m = c.getMethod("myMethod", String.class, int.class); MyAnnotation a = m.getAnnotation(MyAnnotation.class); System.out.println(a.s() + " " + a.i()); // annotation value getters} catch (NoSuchMethodException ex) {}
JSE Built-In MarkerAnnotations
Fromjava.lang
@Override - used only on methods. must override a method from a superclass.
@Deprecated
@SafeVarargs - indicates that no unsafe actions related to a varargs parameter occur. It is used to suppress warnings.
@SuppressWarnings