【问题标题】:Using String.format() as annotation attribute value使用 String.format() 作为注解属性值
【发布时间】:2011-05-19 02:14:34
【问题描述】:

我有一个有许多常量的类:

public class SecurityConstants {
    private static final String HAS_ROLE_TEMPLATE = "hasRole('%s')";

    public static final String ROLE_USER_INTERNAL = "ROLE_USER_INTERNAL";
    public static final String HAS_ROLE_USER_INTERNAL = String.format(HAS_ROLE_TEMPLATE, ROLE_USER_INTERNAL);
}

如果我然后尝试使用HAS_ROLE_USER_INTERNAL 作为@PreAuthorize 注释属性值,像这样@PreAuthorize(SecurityConstants.HAS_ROLE_USER_INTERNAL) 编译器失败:

注解属性的值 PreAuthorize.value 必须是常量 表达

但是,如果我将 HAS_ROLE_USER_INTERNAL 更改为简单的 String,它就可以正常工作:

public static final String HAS_ROLE_USER_INTERNAL = "hasRole('ROLE_USER_INTERNAL')";

使用String.format() 有什么问题?字段是staticfinal,有什么可能出错?

【问题讨论】:

    标签: java annotations constants string-formatting


    【解决方案1】:

    String.format() 的值在编译时是未知的,而 String 文字是。

    由于注释是已编译类的元数据,因此在编译器生成最终的 .class 文件时必须知道它们的值。由于String.format() 的值只有在代码实际运行后才能知道运行,因此编译器不会让您将其用作注释的一部分。

    【讨论】:

    • 是的,好的,但是如果普通的 String 文字支持 Java 格式,那就更好了。 format("hasRole('%s')", ROLE_NAME) 看起来比 "hasRole('" + ROLE_NAME + "')" IMO 好得多......或者我做了太多的 python 编程。 :-)
    • 我知道这真的很晚了,@parxier 您是否考虑过启用@Secured 注释(@EnableGlobalMethodSecurity(securedEnabled=true))?然后你可以做类似@Secured({ROLE_NAME})的事情(角色名称应该有一个明确的ROLE_前缀,例如ROLE_NAME = "ROLE_ADMIN";
    • 遗憾的是,Java 没有像 C++ 这样的 constexpr 关键字 :(
    猜你喜欢
    • 2017-04-25
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多