Custom Annotations with Retention
Defines custom annotations with different retention policies and demonstrates runtime annotation processing via reflection for metadata-driven behavior.
Code
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface AuditLog {
String action();
String level() default "INFO";
}
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
@interface Service {
String value();
}
@Service("userService")
class UserService {
@AuditLog(action = "create", level = "DEBUG")
public void createUser(String name) {
System.out.println("Creating user: " + name);
}
@AuditLog(action = "delete")
public void deleteUser(int id) {
System.out.println("Deleting user: " + id);
}
}
public class CustomAnnotations {
public static void main(String[] args) throws Exception {
Class<?> clazz = UserService.class;
if (clazz.isAnnotationPresent(Service.class)) {
Service svc = clazz.getAnnotation(Service.class);
System.out.println("Service: " + svc.value());
}
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(AuditLog.class)) {
AuditLog log = method.getAnnotation(AuditLog.class);
System.out.println(method.getName() +
" -> action=" + log.action() +
", level=" + log.level());
}
}
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.