为什么注释属性的值应该是常量表达式? [英] Why should the value for an annotation attribute be a constant expression?

查看:34
本文介绍了为什么注释属性的值应该是常量表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

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

我知道根据 JLS,只允许常量表达式作为注释属性的值.但为什么?为什么数据类型匹配还不够?如果要在运行时评估表达式,有什么可能出错的吗?每个规范背后都有逻辑推理吗?

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.

因为 java 是一种静态类型语言(意味着类型在编译时已知),在编译时也知道注释属性数据(元数据)似乎是合理的 - 您正在定义/声明有关注释(扩展名)的数据).

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.

这篇关于为什么注释属性的值应该是常量表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆