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?
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.
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.
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With