How to Define a Custom Annotation:
- Creating a custom annotation in Java involves defining the annotation type using the
@interfacekeyword. - You can specify various elements in the annotation, such as methods that act as attributes, which can have default values.
- Here’s a step-by-step guide to defining a custom annotation:
- Define the Annotation: Use the
@interfacekeyword to create the annotation. - Add Retention Policy: Use
@Retentionto specify how long the annotation is retained (e.g., at runtime, compile-time). - Specify Target: Use
@Targetto define where the annotation can be applied (e.g., methods, classes, fields).
- Define the Annotation: Use the
Example:
Here’s a simple example of defining a custom annotation:
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; // Define the custom annotation@Retention(RetentionPolicy.RUNTIME) // The annotation is available at runtime
@Target(ElementType.METHOD) // The annotation can only be applied to methods
public @interface CustomAnnotation {
String value() default "default"; // An optional element with a default value
int number() default 0; // Another optional element
}
- In this example:
- RetentionPolicy.RUNTIME: The annotation is retained at runtime, allowing it to be accessed via reflection.
- ElementType.METHOD: This annotation can only be applied to methods.
- Elements:
valueandnumberare elements of the annotation with default values.
How to Use the Custom Annotation:
You can use the custom annotation on methods like this:
public class Test { @CustomAnnotation(value = "Hello", number = 5) public void annotatedMethod() { System.out.println("This method is annotated with CustomAnnotation."); } }
Things to Keep in Mind:
- No Constructor: Annotations cannot have constructors.
- Element Types: The elements of an annotation can be of primitive types, String, Class, enums, other annotations, or arrays of these types.
- Retention Policies: Depending on the intended use, you can choose different retention policies (SOURCE, CLASS, or RUNTIME).