是否可以使用注释中的其他值?

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
}

是否有一些技巧可以像我的示例中那样使用另一个值来定义默认值?

简而言之,没有。

默认值必须是常量,原始值或字符串。由于字符串在 Java 中是不可变的,为了将 exception().toString() 连接到前一个字符串,必须创建一个新的字符串。当然,创建新对象不是常量,因此不允许串联。此外,由于 exception().toString() 可以更改,因此 default 值将 永远不会 不变。

这不可能。

注释值在JLS 9.7.1中描述。语言不是很清楚,但基本上值必须是常量(或 "inline" 常量数组):

If T is a primitive type or String, then V is a constant expression (§15.28).

这并不排除字符串连接,但连接的字符串必须是常量,如 JLS 15.28 中所定义。由于 exception().toString() 不是常量(方法的结果永远不是常量),因此 "foo" + exception().toString().

也不是

您真正可以做的唯一技巧是指定一些表示空消息的字符串,并且在调用站点,如果您看到该字符串,则改为 return "The following exception thrown:" + annotation.exception()。空字符串 "" 是该值的一个很好的候选者(但它不能为空)。