·
Define
An annotation is a form of syntactic metadata that can be added to Java source code.
Classes, methods, variables, parameters and Java packages may be annotated.
―Replacement of marker interfaces:
//Before public class Foo implements MarkerInterface {} //Now @MyAnnotation public class Foo {}
―Better metadata management:
//Before:in Javadoc /** * @deprecated As of JDK version 1.1, */ public class DeprecatedApi {} //Now:with annotation @Deprecated(since="1.2", forRemoval=true) public class DeprecatedApi {}
Creating an annotation
Annotations require:
1) A target: this defines where the annotation can be set
2) A retention: this describes up to which step in the compilation process the annotation will be available
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) @interface Bar {}
Annotation parameters
Annotations can define parameters.
Parameters allow to add some level of configuration at the time the annotation is used.
@Target(ElementType.CLASS) @interface Foo { int bar(); Class<? extends Collection> baz() default List.class; String[] qux(); } @Foo(bar = 1, qux = { "a", "b", "c" }) class MyClass {}