Course contentsShow
← Java
Lesson 2422 of 2,87046. AnnotationsFree lesson

Creating Your First Annotation with @interface

Learn the @interface keyword for declaring annotations and understand the fundamental structure of custom annotations.

Creating Your First Annotation with @interface

You'll learn how to declare your own custom annotations using the @interface keyword and understand their basic structure.

What Is an Annotation Declaration?

Until now, you've been using built-in annotations like @Override and @FunctionalInterface. But Java lets you create your own. Think of annotations as custom labels you can attach to code elements—like sticky notes with structured information. When you declare an annotation, you're defining what information that label can hold.

To create an annotation, you use the @interface keyword (not to be confused with regular interface). This special keyword tells Java you're defining an annotation type, not a regular interface.

Basic Syntax

Here's the simplest possible annotation:

public @interface MyAnnotation {
}

That's it! You now have a custom annotation called @MyAnnotation that you can apply to classes, methods, or other code elements:

@MyAnnotation
public class MyClass {
    @MyAnnotation
    public void myMethod() {
    }
}

The Structure

An annotation declaration looks similar to an interface declaration but with @ prefixed. The body can be empty (like above) or contain elements—essentially methods without implementations that define what data the annotation carries:

public @interface Author {
    String name();
    String date();
}

Now you can use it with values:

@Author(name = "Alice", date = "2024-01-15")
public class MyClass {
}

The @interface keyword signals that you're creating metadata structure, not executable code. The compiler treats this specially, allowing it to be processed at runtime through reflection (as you learned in earlier lessons).

Key Takeaway: Use @interface to declare custom annotations; they look like interfaces but create metadata labels, not contracts for implementation.