Defining Custom Java Annotations with @interface
Defining a Custom Annotation: The @interface Keyword
@interface name {
definition
}
name: annotation name
definition: annotation definition
You can define your own annotation using the @interface keyword. For example, the following defines a Version annotation.
Version.java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface Version {
double value();
}
Meta-Annotations
In an annotation definition, annotations can be added to define information about the annotation itself. Such annotations are called meta-annotations.
The types of meta-annotations are as follows.
@Retention@Target@Inherited
@Retention
The range in which annotation information is retained.
| Annotation | Overview |
|---|---|
@Retention(SOURCE) |
The annotation can be used only in source code and disappears after compilation. |
@Retention(CLASS) |
The annotation exists in the .class file but disappears at runtime. |
@Retention(RUNTIME) |
The annotation can be used by the compiler and at runtime. |
@Target
Specifies the targets to which the annotation can be applied.
| Annotation | Overview |
|---|---|
@Target(ElementType.TYPE) |
Can be applied to any element of a class; default value. |
@Target(ElementType.FIELD) |
A specific field of a class. |
@Target(ElementType.METHOD) |
A method of a class. |
@Target(ElementType.PARAMETER) |
A method parameter. |
@Target(ElementType.CONSTRUCTOR) |
A constructor. |
@Target(ElementType.LOCAL_VARIABLE) |
A local variable. |
@Target(ElementType.ANNOTATION_TYPE) |
An annotation type. |
@Inherited
Whether annotation information can be inherited by subclasses.
Annotation Attributes
Under the @interface keyword, specify attributes that can be used in the annotation. Attributes are represented as a set of type and name, like abstract methods.
Attributes defined this way can generally be specified in the form @AnnotationName(attributeName=value, ...). However, when the attribute name is value, the name can be omitted and written as @AnnotationName(value).
For example, the following is an example of an annotationTest method that specifies the Version annotation.
AnnotationSample.java
package com.example.mynavi.object;
public class AnnotationSample {
@Version(1.0)
public void annotationTest() {
System.out.println("Released");
}
}