public class AnnotationTest1 {
@SuppressWarnings("unused")
private void doSomething() {
}
}
In the above example, without the @SuppressWarnings annotation, the compiler would display the following warning message:
"The method doSomething() from the type AnnotationTest1 is never used locally".
package java.lang;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
In the example above, the @Target annotation specifies that the @Override annotation can only be applied to method declarations.
package java.lang;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
String[] value();
}
In the above example, the @Retention annotation specifies that the @SuppressWarnings annotation is only relevant during compilation and should not be retained in the class bytecode.@interface keyword.default keyword.value for convenience.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Annotation1 {
double value() default 10.0;
}
When an annotation has a single element named value, the element name can be omitted when using the annotation.
If a default value is provided and you want to use it, parentheses can be omitted entirely.
public class Test1Annotation1 {
@Annotation1 // Uses default value (10.0)
public Double myVar1;
@Annotation1(1.2) // Shorthand for value = 1.2
public Double myVar2;
@Annotation1(value = 1.3) // Explicit element name
public Double myVar3;
}
Annotations with no elements are called marker annotations and can be used without parentheses.RetentionPolicy.RUNTIME can be accessed at runtime using Java's reflection API.
import java.lang.reflect.Field;
public class Test2Annotation1 {
@Annotation1
public Double myVar1;
@Annotation1(1.2)
public Double myVar2;
@Annotation1(value = 1.3)
public Double myVar3;
public static void main(String[] args) {
Field[] fields = Test2Annotation1.class.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Annotation1.class)) {
Annotation1 annotation = field.getAnnotation(Annotation1.class);
System.out.println("Field: " + field.getName() + ", Value: " + annotation.value());
}
}
}
}
Output:Field: myVar1, Value: 10.0 Field: myVar2, Value: 1.2 Field: myVar3, Value: 1.3