@interface
- Java course
- Advanced
- Lesson 32/82
- 5 min
Learn to define custom annotations with @interface.
Defining an annotation with @interface
To define your own annotation you use the @interface keyword. It is a special kind of type that implicitly extends java.lang.annotation.Annotation.
Example: public @interface Review { String value(); }. The value() inside the braces is an element; it takes a value when the annotation is applied. Elements are written like methods but the compiler treats them as fields. An element may also declare a default value.
Elements and default values
An annotation element is written with a type and a name: String role();. If you do not want to force a value every time, give a starting value with default: String role() default "user";.
Then you can apply @Tag as @Tag (default is used) or @Tag(role = "admin") (value is given). The element type may be a primitive, String, class, enum, annotation, or an array of these.
Practice Define and apply the Tag annotation
Define an @interface Tag with String value() default "empty". Apply @Tag("vip") to the Customer class. In main, print Tag ready with System.out.println.
Starter code
// Define the Tag annotation
// Apply Tag to the Customer class
// Print to the screen in mainSample solution
@interface Tag {
String value() default "empty";
}
@Tag("vip")
class Customer { }
public class TagDemo {
public static void main(String[] args) {
System.out.println("Tag ready");
}
}Expected output
Tag ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the annotation elements
| Term | Meaning |
|---|---|
@interface |
Definition keyword |
String value() |
An element |
default |
Default value |
@Review("x") |
Application |
2 Which keyword is used to define your own annotation?
- interface
- @Annotation
- class
- @interface Correct answer
Explanation: @interface defines an annotation; a plain interface does not.
3 Complete the @interface definition
public @____ Tag { String value() default "empty"; }
public @interface Tag { String value() default "empty"; }
Explanation: @interface defines the Tag annotation.