This document discusses Java annotations. It explains that annotations provide metadata that can add value to code and can be applied to classes, methods, and variables. Common built-in annotations like @Override and @FunctionalInterface are described. The document also covers defining custom annotations by using the @interface syntax and defining annotation elements. Finally, it discusses annotations that can be applied to other annotations, such as @Target, @Retention, and @Repeatable.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
7 views17 pages
Annotations
This document discusses Java annotations. It explains that annotations provide metadata that can add value to code and can be applied to classes, methods, and variables. Common built-in annotations like @Override and @FunctionalInterface are described. The document also covers defining custom annotations by using the @interface syntax and defining annotation elements. Finally, it discusses annotations that can be applied to other annotations, such as @Target, @Retention, and @Repeatable.
• As stated earlier, annotations have a lot in common with
interfaces; for example, a marker annotation has no elements (a marker interface has no methods). Annotations, as with interfaces, can be applied to unrelated classes.
• In fact, we annotate our annotation with @interface.
• public @interface MyAnnotation {} // marker annotation
TYPE Interfaces, enums, classes, annotations. METHOD Method declarations PARAMETER Constructor and method parameters FIELD Instance and static variables CONSTRUCTOR Constructor declarations LOCAL_VARIABLE Local variables ANNOTATION_TYPE Annotations TYPE_USE Anywhere there is a Java data type. This includes where types are used e.g. object creation with new.
SOURCE Source file only, compiler discards it. CLASS Stored in the .class file but not available at runtime. This is the default compiler behaviour. RUNTIME Stored in the .class and available at runtime (via reflection).
@Repeatable • This annotation enables us to specify an annotation on a type more than once.
• This is useful if you wanted to use the same annotation but
with different values each time; thus, it is not of much use for marker annotations (which have no elements).
• Requires two annotations:
1. A container annotation which has a value() array element; the type of the array is the annotation you want to repeat. 2. The annotation to want to repeat; which is annotated with: @Repeatable(ContainerAnnotationName.class) 16