Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...