审查生成的角色调度器

来自 注解
Java 25 LTS 高级 6分钟 找出 5处问题

在这段生成的角色调度器用于保护管理操作前进行审查。

调度带注解的 public 方法,包括继承方法;按拒绝优先策略校验角色值;保留有用的失败信息;并高效处理重复调用。

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

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误