如何使用局部变量注释进行Wicket授权?

时间:2012-12-13 22:08:26

标签: java annotations wicket wicket-1.5

我正在为Wicket 1.5.x推出自己的IAuthorizationStrategy我为isInstantiationAuthorized()使用的页面设置了类型注释。它运作良好,我也想使用isActionAuthorized()的注释。理想情况下,我希望能够注释局部变量,然后检查我的AuthStrategy中的注释。从我读到的内容变量Annotation不起作用。

是否存在任何类型的已知工作,可能是某种编译时间注释处理将带注释的局部变量转换为“匿名”子类,并将注释作为类型注释?

对于记录,我试图使用的注释如下所示:

@Retention(RetentionPolicy.Runtime)
@Target(ElementType.Type, ElementType.LOCAL_VARIABLE)
public @interface AdminOnly
{
  int isVisible() default 0;
  int isEnabled() default 1;
}

更新

所以基于@XaviLópez'es回答我希望做的事情并非完全可能。 注释的LocalVariables 应该在编译时可用。有没有什么方法可以使用它们作为锅炉电镀的快捷方式,可以在Wicket Examples或优秀的Apache Wicket Cookbook中找到元数据代码示例?

1 个答案:

答案 0 :(得分:0)

前段时间我和Wicket 1.3.x一直在努力解决类似的问题,并且没有找到任何通过注释实现此目的的方法。无法在运行时保留局部变量的注释,如JLS(9.6.3.2. @Retention)中所述:

  

本地变量声明的注释永远不会保留在二进制表示中。

在这个相关问题中:How can I create an annotation processor that processes a Local Variable?他们讨论了LAPT-javac,修补了javac版本以允许此操作。在他们的网站上有Type Annotations Specification (JSR 308)的链接,希望能够解决这个问题(JDK 8?)。

我最终定义了一个带有相关功能代码的普通旧界面:

public interface RestrictedComponent {
    Integer getFunction();
}

这种方法的主要问题是,不可能使特定类的即时匿名子类实现其他接口(例如Component c = new TextField() implements AdminOnly { }),但您始终可以定义刚刚实现的Component扩展一个班级RestrictedComponent

public abstract class RestrictedTextField extends TextField implements RestrictedComponent { } 

最后,我最终实现了一个RestrictedContainer,它只是将WebMarkupContainer子类化,并将每个安全组件放在一个组件中,并在标记中使用<wicket:container>对其进行建模。

public class RestrictedContainer extends WebMarkupContainer implements RestrictedComponent {
    private final Integer function;
    public RestrictedContainer(String id, IModel model, final Integer function) {
        super(id, model);
        this.function = function;
    }
    public RestrictedContainer(String id, final Integer funcionalitat) {
        super(id);
        this.function = function;
    }
    public Integer getFunction() {
        return function;
    }
}

然后在授权策略中检查component instanceof RestrictedComponent并返回truefalse,具体取决于相关功能的用户权限。

相关问题