Why can't I calculate a constant annotation parameter?

Why does the following code compile:

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

But the following code does not work (at least with the Eclipse compiler):

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

The Eclipse compiler returns the following error:

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

+4
source share
1 answer

The constant expression required by Eclipse in the error message is an expression of the compile time constant (and not just the final variable), and a call to the UUID.randomUUID().toString(); method. UUID.randomUUID().toString(); must be evaluated at runtime.

As you write dynamic annotation values ​​using JavaAssist at runtime , you will lose the β€œreadable” annotation function.

+4
source

Source: https://habr.com/ru/post/1394828/


All Articles