4

Why does the following code compile:

final String name = "works";
@Provides @Named(name) String provideAboutTitle() {
   return "ABC";
}

But the following code fails (at least with Eclipse's compiler):

final String name = UUID.randomUUID().toString();
@Provides @Named(name) String provideAboutTitle() {
   return "ABC";
}

Eclipse's compiler returns the following error:

The value for annotation attribute Named.value must be a constant expression

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246

1 Answers1

4

The constant expression Eclipse demands in the error message is a compile-time constant expression (not just a final variable) and the method call UUID.randomUUID().toString(); needs to be evaluated at run-time.

While you can write dynamic annotation values using JavaAssist at runtime, you will lose "easy to read" feature of the annotations.

Asciiom
  • 9,867
  • 7
  • 38
  • 57
Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
  • see also here for possible solutions: http://stackoverflow.com/questions/13253624/how-to-supply-enum-value-to-an-annotation-from-a-constant-in-java – atom88 Jan 19 '17 at 16:23