Rol*_*der 17 java enums annotations
目前我正在为Java Swing开发一个基于注释的绑定框架,它使用JGoodies Binding.不幸的是,我坚持使用JRadioButton绑定的注释.我想要做的是指定一个包含特殊值(枚举)的模型的属性名称.如果此属性具有特定值,则应选择单选按钮.现在我想在注释中指定值,如下所示:
@RadioButtonBinding(property = "selectedItem", selectedValue = MyEnum.FIRST)
JRadioButton firstButton
@RadioButtonBinding(property = "selectedItem", selectedValue = MyEnum.SECOND)
JRadioButton secondButton
Run Code Online (Sandbox Code Playgroud)
但是,我不知道如何声明注释以允许上面和任何其他枚举.我的第一个猜测就是这个,但我了解到注释属性不能是通用的:
@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();
}
Run Code Online (Sandbox Code Playgroud)
任何想法如何解决这个问题?
它不会按照你想要的方式工作。正如您所发现的,您只能在注释中使用非常简单的返回类型。此外,尝试通过滥用 String 之类的方法来绕过这些限制是行不通的,因为您需要使用常量表达式来初始化注释的值。
我认为最接近的方法是使用字符串进行初始化,然后使用代码与枚举的 name() 进行比较。但是你的类型安全消失了......