Middle
How to create a custom annotation in Java?
sobes.tech AI
Answer from AI
- Declare an annotation with
@interface. - Define elements (methods) of the annotation. These methods have no parameters and return primitive types,
String,Class,enum, another annotation, or an array of these types. - Specify
@Targetto define where the annotation can be applied (class, method, field, etc.). - Specify
@Retentionto define how long the annotation is retained (at compile time, runtime, etc.). - (Optional) Use
@Documentedto include the annotation in Javadoc. - (Optional) Use
@Inheritedto allow inheritance of the annotation by subclasses.
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Retention(RetentionPolicy.RUNTIME) // Available at runtime
@Target(ElementType.METHOD) // Applicable to methods
public @interface MyCustomAnnotation {
String value() default "default value"; // Element with default value
int count(); // Required element
}
Usage example:
public class MyClass {
@MyCustomAnnotation(count = 10) // Using custom annotation
public void myMethod() {
// Some code
}
}