Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums and Annotations

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() {
}
like image 671
PeterMmm Avatar asked Mar 27 '10 19:03

PeterMmm


People also ask

What is difference between enum and enumeration?

enum is a syntactic sugar that allows for meaningful constants; Enumeration is a class that provides way to go through a collection.

What is the meaning of enums?

Enum is short for "enumerations", which means "specifically listed".

What is enum and 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.

Why enums are better than strings?

They are type safe and comparing them is faster than comparing Strings.


2 Answers

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";
};
like image 136
leedm777 Avatar answered Sep 23 '22 09:09

leedm777


Make the value in the annotation of type E:

@interface A {
   E value();
}

Then you can use

@A(E.a)
like image 27
Yardena Avatar answered Sep 23 '22 09:09

Yardena