Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum in Annotations

I have an annotation I can't change which expects two String arguments.

I'd like to use it like this:

@RequestMapping( MyUrls.FOO.a, MyUrls.FOO.b )

This is how I imagined implementing it

public enum MyUrls {
    FOO("a", "b"), 
    BAR("c", "d");

    public String a, b;
    MyUrls(String a, String b) {
        this.a = a;
        this.b = b;
    }
}

This doesn't work since a or b can't be statically resolved.

What alternatives do I have which are nicer than:

class MyUrls {
    public static String FOO_A = "";
    public static String FOO_B = "";
    // ...
}
like image 910
Johan Sjöberg Avatar asked Mar 29 '12 12:03

Johan Sjöberg


People also ask

What is enum and annotation in Java?

Enums could be treated as a special type of classes and annotations as a special type of interfaces. The idea of enums is simple, but quite handy: it represents a fixed, constant set of values. What it means in practice is that enums are often used to design the concepts which have a constant set of possible states.

What is enum with example?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

What is enum used for?

An enumeration, or Enum , is a symbolic name for a set of values. Enumerations are treated as data types, and you can use them to create sets of constants for use with variables and properties.

What does enum stand for?

In computer programming, an enumerated type (also called enumeration, enum, or factor in the R programming language, and a categorical variable in statistics) is a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type.


1 Answers

Although your question does not look like a question but as a declaration, I agree with you. You cannot use enum members when you are defining annotations. Only "real" constants, i.e. static final fields and constant expressions are applicable. So, there is no good alternative right now.

like image 135
AlexR Avatar answered Oct 11 '22 13:10

AlexR