[英]Is it possible to use another values from annotations?
我有以下注释:
public @interface ExceptionPair {
public Class<?> exception();
public String message()
default "The following exception thrown:" + exception().toString();
//error: not a constant
}
是否有一些技巧可以像我的示例中那样使用另一个值来定义默认值?
这是不可能的。
批注值在JLS 9.7.1中描述。 语言不是很清楚,但是基本上值必须是常量(或常量的“内联”数组):
如果T是原始类型或String,则V是常数表达式(第15.28节)。
但这并不排除字符串串联,但是串联的字符串必须是常量,如JLS 15.28所定义。 由于exception().toString()
不是常量(方法的结果永远不是常量),因此"foo" + exception().toString()
也不是常量。
您真正能做的唯一技巧是指定一些表示空消息的字符串,然后在调用站点中,如果看到该字符串,则返回"The following exception thrown:" + annotation.exception()
。 空字符串""
是该值的最佳候选者(尽管不能为null)。
简而言之,没有。
默认值必须是常量,可以是原语或字符串。 由于字符串在Java中是不可变的,因此为了将exception().toString()
连接到先前的字符串,必须创建一个新的字符串。 当然,创建新对象不是常量,因此不允许串联。 此外,由于exception().toString()
可以更改,因此default
值永远不会恒定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.