At the moment I am developing an annotation-based binding-framework for Java Swing that uses JGoodies Binding under the hood. Unfortunately I am stuck with an annotation for a JRadioButton-binding. What I want to do is specify a property-name of a model which holds a special value (enum). The radio-button shall be selected if this property has a specific value. Now I want to specify the value in the annotation like this:
@RadioButtonBinding(property = "selectedItem", selectedValue = MyEnum.FIRST)
JRadioButton firstButton
@RadioButtonBinding(property = "selectedItem", selectedValue = MyEnum.SECOND)
JRadioButton secondButton
However, I do not know how to declare the annotation to allow the above and any other enum, too. My first guess was this, but I learned that annotation attributes cannot be generic:
@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();
}
Any ideas how to solve this?
An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.
You can reference the class of your enum type in a @Type annotation on your entity attribute. This is a good approach if you only use the type on one entity attribute. When you use this mapping, Hibernate uses the EnumTypePostgreSql to map the Rating value to a PostgreSQL-specific enum type.
The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields.
It's not going to work the way you want it to. As you've found out, you can only use really plain return types in annotations. Additionally, trying to get around these restrictions by doing stuff like abusing String isn't going to work because you need to be using a constant expression for initialising your annotation's values.
I think the closest you're going to get is to initialise with a String and then use code to compare with the enum's name(). But there goes your type safety...
If your enums can implement all the same interface, you may find useful this question "Coding tip - intersection types and java enums"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With