Middle
Tell about your experience writing custom annotations in Java.
sobes.tech AI
Answer from AI
In Java, I created custom annotations for various purposes, such as data validation or configuring component behavior. To create an annotation, the keyword @interface is used. You can specify parameters with default values, as well as define the scope and lifetime of the annotation using meta-annotations @Target and @Retention.
Example of a custom annotation for field validation:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface NotEmpty {
String message() default "Field must not be empty";
}
This annotation can then be read via reflection to implement validation logic. This approach helps centralize and simplify validation or configuration without modifying the main code.