Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should the value for an annotation attribute be a constant expression?

I am having the following piece of code

 @UIUnitTimeout(8*60*1000) // works
 @UIUnitTimeout(TimeUnit.MINUTES.toMillis(8)) // does not work

I know that according to the JLS only constant expressions are allowed as values to annotation attributes. But why? Why it isn't sufficient if the data types match? Is there anything that could possibly go wrong if the expressions were to be evaluated at runtime? Does every specification have a logical reasoning behind?

like image 951
Shiva Kumar Avatar asked Feb 18 '13 07:02

Shiva Kumar


2 Answers

An annotation is like a type extension or metadata about the type.

Because java is a statically typed language (meaning that types are known at compile time), it seems reasonable that annotation attribute data (metadata) be known at compile time too - you're defining/declaring data about the annotation (extension).

And as a purely practical point, for annotation processing, which is a compile-time (optional) step, attribute data must be known at compile time - you haven't yet reached a runtime environment, yet you need the attribute data.

like image 197
Bohemian Avatar answered Oct 20 '22 00:10

Bohemian


Annotation preprocessing requires knowning the value of the annotation before executing the annotated code. In addition, Annotation definitions are themselves anotated with @Retention, which has a value of RetentionPolicy (if not specified, it defaults to CLASS).

Therefore there are 3 different "kinds" of annotations, and only those annotations declared as RUNTIME will be available when the program is executed. (But their value must be constant, so that they remain defined without executing the associated code.)

CLASS Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.

RUNTIME Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.

SOURCE Annotations are to be discarded by the compiler.

.

like image 38
Javier Avatar answered Oct 20 '22 02:10

Javier