Review generated role dispatcher

from Annotations
Java 25 LTS advanced 6 min 5 issues to find

Review this generated role-aware dispatcher before it protects administrative operations.

Dispatch annotated public methods, including inherited ones, enforce role values with a deny-by-default policy, preserve useful failures, and handle repeated calls efficiently.

Java
import java.lang.annotation.*;
import java.lang.reflect.Method;

@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
@interface RequiresRole { String value(); }

class AccountAdmin {
    @RequiresRole("admin")
    public void closeAccount() {}
}

public class GeneratedDispatcher {
    static void dispatch(Object target, String methodName, String role)
            throws Exception {
        Method method = target.getClass()
                .getDeclaredMethod(methodName);
        RequiresRole required = method.getAnnotation(RequiresRole.class);
        if (required != null && role != required.value()) {
            throw new SecurityException("wrong role");
        }
        method.setAccessible(true);
        method.invoke(target);
    }
}

generated code is illustrative, not from any one model

Open in playground
Report an error