有没有申报任何* *枚举的注释属性的方法? [英] Is there a way to declare an annotation attribute for *any* enum?

查看:359
本文介绍了有没有申报任何* *枚举的注释属性的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在开发一个使用的JGoodies引擎盖下绑定的Java Swing基于注解结合的框架。不幸的是我坚持的一个JRadioButton结合注解。
我想要做的就是指定拥有一个特殊的值(枚举)模型的属性名称。如果这个属性具有特定值的单选按钮应选择。现在我要指定在这样注解的值:

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?

推荐答案

这是行不通的,你想让它的方式。当你找到了,你只能使用真正平原标注返回类型。此外,试图做的东西像滥用字符串是行不通的,因为你需要使用一个恒定的前pression用于初始化注记的价值观来绕过这些限制。

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.

我想你会得到最接近的是一个字符串初始化,然后使用code与枚举的名称进行比较()。但是,去你的类型的安全...

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

这篇关于有没有申报任何* *枚举的注释属性的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆