Custom annotations are user-defined annotations that you can create and apply in your Java programs to provide meaningful metadata. These annotations do not change the logic of the program but can be used to:
- Generate code at compile-time
- Perform validation at runtime
- Inject dependencies (used in frameworks like Spring)
- Support configuration and documentation
Why Use Custom Annotations?
- Cleaner code: Avoids cluttering code with repeated boilerplate.
- Metadata-driven: Promotes declarative programming.
- Powerful tooling: Used with reflection, bytecode manipulation, or frameworks.
- Customization: Tailored to your specific domain logic or architectural needs.
Syntax to Create a Custom Annotation
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME) // How long the annotation should be retained
@Target(ElementType.METHOD) // Where the annotation can be used
public @interface MyAnnotation {
String value(); // Single element
int count() default 1; // Default value for an optional element
}
Code language: PHP (php)
Example 1: Simple Custom Annotation
import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface TestInfo { String author(); String date(); } public class Demo { @TestInfo(author = "LotusJavaPrince", date = "2025-05-25") public void display() { System.out.println("Custom annotation applied"); } } //This annotation is used to provide metadata for the display() method.
Example 2: Reading Custom Annotations via Reflection(From above Demo class)
import java.lang.reflect.Method; public class AnnotationReader { public static void main(String[] args) throws Exception { Class<Demo> clazz = Demo.class; for (Method method : clazz.getDeclaredMethods()) { if (method.isAnnotationPresent(TestInfo.class)) { TestInfo info = method.getAnnotation(TestInfo.class); System.out.println("Author: " + info.author()); System.out.println("Date: " + info.date()); } } } } /* Author: LotusJavaPrince Date: 2025-05-25 */
Best Practices
- Always define
@Retention
and@Target
for clarity. - Keep annotation usage intuitive and meaningful.
- Use reflection or processors responsibly for performance.
- Document your custom annotations for other developers.
Custom annotations are a powerful feature in Java that enrich code semantics and enable declarative programming. Whether you’re building a simple utility or an enterprise framework, custom annotations make your code more expressive, cleaner, and easier to maintain. Mastering them opens the door to advanced techniques like annotation processing, AOP, and custom validation.