代码之家  ›  专栏  ›  技术社区  ›  Roland Schneider

有没有方法为*any*枚举声明注释属性?

  •  16
  • Roland Schneider  · 技术社区  · 17 年前

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

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

    有什么解决办法吗?

    3 回复  |  直到 14 年前
        1
  •  3
  •   Jon Bright    17 年前

    它不会按你想要的方式工作。正如您所发现的,您只能在注释中使用真正普通的返回类型。此外,试图通过滥用字符串之类的操作来绕过这些限制是行不通的,因为您需要使用常量表达式来初始化注释的值。

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

        2
  •  1
  •   Community Mohan Dere    9 年前

    如果枚举可以实现所有相同的接口,您可能会发现这个问题很有用。” Coding tip - intersection types and java enums

        3
  •  0
  •   StaxMan    17 年前

    我试图解决这个完全相同的问题,据我所知,这是不可能的。 这真是个麻烦事。

    在我的例子中,我想指定@version annotation,在这里可以使用任何枚举,并且可以按序号比较枚举值(以查找版本的顺序)。看起来我需要像其他一些框架(如我认为的Guice)那样做,使用double;有点难看,但对于>=和<=检查可以正常工作。