Overloading Java annotations?

In my project, I defined an annotation similar to the following:
(Lowering @Retention, @Targetfor short)

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

Ever since he started writing, our needs have changed, and now I have defined an enumeration that I want to use instead of a string:

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

In order not to update each instance of this annotation, I would like to be able to create an annotation using Stringor a member enum Particlewithout having to update each instance of this annotation to indicate an attribute. However, since we are defining annotation attributes rather than 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, ...})

Also tried:

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

Is there a way to do this that doesn't require returning and editing a huge amount of code?

+3
3

- . , . .

, , , , . , , .

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

DecaysToV2 - , :

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; }
} 
+4

(, @DecaysToParticle) .

+2

,

enum Particle {
    ELECTRON("Electron"),
    ...

    private String name;
    private Particle(String name) {
        this.name = name;
    }
    public String getName() {return name;}
}

( , apporach ).

Also, I don’t understand how much code needs to be changed, because (I think) your sentences will not compile, I hope that this is not what your code actually looks like.

+1
source

Source: https://habr.com/ru/post/1762995/


All Articles