import java.lang.annotation.*;
// Simple annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogExecution {
}
// Annotation with parameters
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Author {
String name();
String date() default "2024-01-01";
String[] tags() default {};
}
// Marker annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Serializable {
}
// Single-value annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MaxLength {
int value();
}
// Annotation with enum parameter
public enum Priority {
LOW, MEDIUM, HIGH
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Scheduled {
Priority priority() default Priority.MEDIUM;
int interval() default 60;
}
// Using annotations
@Author(name = "John Doe", tags = {"utility", "helper"})
public class UtilityClass {
@LogExecution
@Scheduled(priority = Priority.HIGH, interval = 30)
public void performTask() {
// Method implementation
}
@MaxLength(100)
private String description;
}
// Annotation processor
public class AnnotationProcessor {
public static void processAnnotations(Object obj) {
Class<?> clazz = obj.getClass();
if (clazz.isAnnotationPresent(Author.class)) {
Author author = clazz.getAnnotation(Author.class);
System.out.println("Author: " + author.name());
}
for (var method : clazz.getMethods()) {
if (method.isAnnotationPresent(LogExecution.class)) {
System.out.println("Logging execution of: " + method.getName());
}
}
}
}