Annotations
Custom Annotations
Learn to declare custom annotations, define parameters, and set default values.
Interview: Commonly tested on annotation declaration syntax, permitted parameter types, and default values.
Java allows declaring custom annotations using the @interface keyword. Custom annotations can hold key-value attributes to supply metadata properties to runtime frameworks.
Core Idea
Custom annotations declare attributes as parameterless methods that can optionally have default values.
Why It Matters
Allows designing custom routing or permission rules (e.g. @RequiresRole) for enterprise frameworks.
Interview Lens
Tests permitted annotation parameter types and default value rules.
Custom Annotation Constraints
When declaring attributes inside custom annotations:
- Allowed Types: Only primitives,
String,Class, enums, other annotation types, and arrays of these types are permitted. Complex objects or nested collections are not allowed. - Defaults: You can specify default values using the
defaultkeyword. - Value Attribute: If an annotation contains a single attribute named
value(), callers can omit the key name when declaring it (e.g.@MyAnnotation("test")).
Code Walkthrough
This class declares a custom annotation representing database columns, with default settings.
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Column { String name(); // Required parameter boolean nullable() default true; // Optional with default value int length() default 255; }
Interview-Relevant Information
Q: Can custom annotation parameters have null as a default value?
Answer: No. Annotation attributes cannot be null. This is a design constraint in the Java language specification. If you want to represent an unassigned state, you must use sentinel values like empty strings (default "") or negative values.
Quick Checklist
What types can be attributes inside annotations? Can you use null as a default? If yes, you understand custom annotations.
Use Cases
Creating ORM annotation parameters for entity fields.
Custom testing frameworks to label execution categories (@TestCategory).
Common Mistakes
Defining complex class types as attributes (only primitives, String, Class, enums, and arrays are allowed).
Forgetting to set a default value when a parameter should be optional, forcing callers to specify it on every tag.