Enumerations and Annotations

I want to use annotation in compiled form.

To pass the value () to the annotation, I want to use a string representation of the enumeration.

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(Ea) void bar() { // C2: no chance, it won't compile @A(EatoString()) void bar2() { } // C3: this is ok @A("a"+"b") void bar3() { } // C4: is constant like C3, is'nt it ? @A(""+Ea) void bar4() { } } @interface A { String value(); } 

Update

I need a String type in @A.

What I can do is

 @A("" + 1) void foo() { } 

But here, the compiler claims that the value of the attribute must be constant. Is'nt Ea Permanent?

 @A("" + Ea) void foo() { } 
+7
java annotations
source share
2 answers

The problem is that you are smarter than the compiler :-)

Ea is a constant, but EatoString() not. It seems like it should, but the compiler can't figure it out.

The reason that "a"+"b" and "" + 1 is because the compiler is smart enough to generate constants at compile time.

When he sees "" + Ea , he uses EatoString() . Calling toString() enough to disable it.

Should E be an enumeration? You can try:

 public final class E { public static final String a = "a"; public static final String b = "b"; }; 
+9
source share

Make a value in type E annotation:

 @interface A { E value(); } 

Then you can use

 @A(Ea) 
+7
source share

All Articles