Sobes.tech
Middle

How to create a custom annotation in Java?

sobes.tech AI

Answer from AI

  1. Declare an annotation with @interface.
  2. 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.
  3. Specify @Target to define where the annotation can be applied (class, method, field, etc.).
  4. Specify @Retention to define how long the annotation is retained (at compile time, runtime, etc.).
  5. (Optional) Use @Documented to include the annotation in Javadoc.
  6. (Optional) Use @Inherited to 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
    }
}
How to create a custom annotation in Java? — Java - sobes.tech