Java注释超载? [英] Java Annotation Overloading?

查看:206
本文介绍了Java注释超载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目,我已经定义了类似下面的注释:结果
(省略 @Retention @Target 为了简洁)

In my project, I have defined the an annotation similar to the following:
(Omitting @Retention, @Target for brevity)

public @interface DecaysTo {
    String[] value();
}

由于最初写它,我们的需求已经改变,现在我已经定义,我希望能够到位的字符串使用一个枚举:

Since originally writing it, our needs have changed and I have now defined an enum that I want to be able to use in place of the string:

public enum Particle {
    ELECTRON,
    ANTIELECTRON,
    NEUTRINO,
    ANTINEUTRINO,
    ...
}

要避免更新此标注的每一个实例,我希望能够构建批注与的一个字符串枚举粒子没有的无需更新此注释的每个实例指定属性的成员。但是,由于我们定义注解的属性,而不是构造函数,这似乎是不可能超载了。

To avoid updating every instance of this annotation, I would like to be able to construct the annotation with either a String or a member of enum Particle without having to update every instance of this annotation to specify the attribute. However, since we define the annotation's attributes, and not constructors, it seems impossible to overload it.

// In a perfect world, either of these would work ...
public @interface DecaysTo {
    String[] value();
    Particle[] value();
}

@DecaysTo({"Electron", ...})
@DecaysTo({Particle.ELECTRON, ...})

// without having to explicitly specify which attribute to set:
public @interface DecaysTo {
    String[] stringVals();
    Particle[] enumVals();
}

@DecaysTo(stringVals = {"Electron", ...})
@DecaysTo(enumVals = {Particle.ELECTRON, ...})

还企图:

public @interface DecaysTo {
    Object[] value();
}

的方式做到这一点,这并不涉及通过回去和编辑code的大量?

Is there any way to do this that doesn't involve going back through and editing an enormous amount of code?

推荐答案

最好的办法是查找和替换所有previous注解。你不想老的设计身边萦绕。保持整个重构干净code基地。

The best way is to find and replace all previous annotations. You don't want old design lingering around. Keep a clean code base throughout refactorings.

假如你不想这样做,或者你没有自己使用的注解code,你应该保持2注释类型。在你的注释处理code,你看这两个,如果旧的使用,将其转换成新的。

Suppose you don't want to do that, or you don't own the code that use the annotation, you should keep two annotation types. in your annotation processing code, you look for both, and if the old one is used, convert it to the new one.

DecaysToV2 anno = getAnnotation( DecaysToV2.class );
if(anno = null)
{
    DecaysTo anno_old = getAnnotation( DecaysTo.class );
    if(anno_old!=null)
       anno = convert (anno_old);
}

DecaysToV2只是一个接口,你可以IMPL:

DecaysToV2 is just an interface which you can impl:

DecaysToV2 convert( DecaysTo old )
{
    DecaysToV2Impl impl = new DecaysToV2Impl();
    impl.value = ...
    return impl;
}
static class DecaysToV2Impl implements DecaysToV2
{
    Particle[] value;
    public Particle[] value(){ return this.value; }
} 

这篇关于Java注释超载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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