java - 有没有办法为 *any* 枚举声明注释属性?

标签 java enums annotations

目前我正在为使用 JGoodies Binding 的 Java Swing 开发一个基于注解的绑定(bind)框架。在引擎盖下。不幸的是,我坚持使用 JRadioButton 绑定(bind)的注释。 我想要做的是指定一个模型的属性名称,它包含一个特殊值(枚举)。如果此属性具有特定值,则应选择单选按钮。现在我想像这样在注释中指定值:

@RadioButtonBinding(property = "selectedItem", selectedValue = MyEnum.FIRST)
JRadioButton firstButton

@RadioButtonBinding(property = "selectedItem", selectedValue = MyEnum.SECOND)
JRadioButton secondButton

但是,我不知道如何声明注释以允许上述和任何 其他枚举。我的第一个猜测是这样的,但我了解到注释属性不能是通用的:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface RadioButtonBinding {

    /** The model-property to which the selected value is bound */
    String property();

    // Idea 1: Specifying the enum class and the enum constant as String - works but is not typesafe

    Class<? extends Enum<?>> enumClass();

    String enumConstantName();

    // Idea 2: Directly specifying the enum constant - gives a compile-time error

    <T extends Enum<T>> T enumValue();

}

有什么解决办法吗?

最佳答案

它不会按照您希望的方式工作。正如您所发现的,您只能在注释中使用真正简单的返回类型。此外,尝试通过滥用 String 之类的方式来绕过这些限制是行不通的,因为您需要使用常量表达式来初始化注释的值。

我认为最接近的方法是使用字符串初始化,然后使用代码与枚举的 name() 进行比较。但是你的类型安全......

关于java - 有没有办法为 *any* 枚举声明注释属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1037531/

相关文章:

java - 如何向 JUNIT 测试套件添加方法..?

java - Java 不支持枚举上的协变返回类型吗?

查找表的sql性能

java - 对 Egit 的行为感到困惑

javascript - typescript 中的字符串枚举

java - 条纹中默认的另一个枚举值

java - 根据变量的注释为变量赋值

java : annotations before method parameters

java - 如何从 HashMap 的数组中获取索引?

java - 编辑像素值