Custom Annotations with Retention

Defines custom annotations with different retention policies and demonstrates runtime annotation processing via reflection for metadata-driven behavior.

JavaConfig Management

Code

snippet
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());
            }
        }
    }
}

How it works

The working surface is the classes AuditLog, Service, UserService and CustomAnnotations and the functions createUser and deleteUser — everything else is wiring.

Repetition is confined to for (Method method : clazz.getDeclaredMethods()) — the rest of the file is straight-line.

Applying it

The main signature is written as public void createUser(String name)

The demo output is labeled (Creating user:, Deleting user:, Service:), so each line traces straight back to the statement that printed it.

Statements that matter

AuditLog log = method.getAnnotation(AuditLog.class);
Service svc = clazz.getAnnotation(Service.class);
@AuditLog(action = "create", level = "DEBUG")
public void createUser(String name) {
    System.out.println("Creating user: " + name);
}

Interactive Tools for This Topic

FAQ

What does Custom Annotations with Retention print when run?
Invoke the file as-is — the `Creating user:`, `Deleting user:`, `Service:` prefixes identify which step printed each line.