有没有办法为* any * enum声明一个注释属性?

时间:2009-06-24 10:23:11

标签: java enums annotations

目前我正在为Java Swing开发一个基于注释的绑定框架,它使用了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 个答案:

答案 0 :(得分:3)

它不会像你想要的那样工作。正如您所知,您只能在注释中使用非常简单的返回类型。此外,尝试通过执行诸如滥用String之类的操作来解决这些限制是行不通的,因为您需要使用常量表达式来初始化注释的值。

我认为你最接近的是用String初始化然后使用代码与枚举的名称()进行比较。但是你的类型安全了...

答案 1 :(得分:1)

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

答案 2 :(得分:0)

我试图解决这个完全相同的问题,据我所知,它无法完成。 这是一个真正的无赖。

就我而言,我想指定@Version注释,其中可以使用任何枚举,并且可以通过序数比较枚举值(以查找版本的排序)。看起来我需要做一些其他框架(比如我认为的Guice)做的事情并使用双打代替;有点难看,但适用于&gt; =和&lt; =检查。

相关问题