I want to use an Annotation in compile-safe form.
To pass the value() to the Annotation i want to use the String representation of an enum.
Is there a way to use @A with a value from enum E ?
public class T {
public enum E {
a,b;
}
// C1: i want this, but it won't compile
@A(E.a)
void bar() {
// C2: no chance, it won't compile
@A(E.a.toString())
void bar2() {
}
// C3: this is ok
@A("a"+"b")
void bar3() {
}
// C4: is constant like C3, is'nt it ?
@A(""+E.a)
void bar4() {
}
}
@interface A {
String value();
}
Update
I need the String type in @A.
The point is i can do this
@A("" + 1)
void foo() {
}
But here the compiler claims "attribute value must be constant". Is'nt E.a constant ?
@A("" + E.a)
void foo() {
}
enum is a syntactic sugar that allows for meaningful constants; Enumeration is a class that provides way to go through a collection.
Enum is short for "enumerations", which means "specifically listed".
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.
They are type safe and comparing them is faster than comparing Strings.
The problem is that you're smarter than the compiler :-)
E.a
is a constant, but E.a.toString()
is not. It looks like it should be, but the compiler can't figure that out.
The reason why "a"+"b"
and "" + 1
work is that the compiler is smart enough to generate the constants at compile time.
When it sees "" + E.a
, it uses E.a.toString()
. The call to toString()
is enough to throw it off.
Does E have to be an enum? You could try:
public final class E {
public static final String a = "a";
public static final String b = "b";
};
Make the value in the annotation of type E:
@interface A {
E value();
}
Then you can use
@A(E.a)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With