views:

664

answers:

3

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(selectedProperty = "selectedItem", selectedValue = MyEnum.FIRST)
JRadioButton firstButton

@RadioButtonBinding(selectedProperty = "selectedItem", selectedValue = MyEnum.FIRST)
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 {

    String selectedItem();

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

    String enumConstantName();

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

}

Any ideas how to solve this?

+1  A: 

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...

Jon Bright
+1  A: 

If your enums can implement all the same interface, you may find useful this question "Coding tip - intersection types and java enums"

diega
Unfortunately not, but thank's for the tip anyway.
Roland Schneider
A: 

I was trying to solve this exact same problem, and as far as I know, it can not be done. It's a real bummer.

In my case, I wanted to specify @Version annotation, where any enumeration can be used, and enum values can be compared by ordinal (to find ordering of versions). Looks like I need to do what some other frameworks (like Guice I think) do and use doubles instead; bit ugly, but works ok for >= and <= checks.

StaxMan