有人可以解释为什么字符串和类注释参数的预期不同吗?为什么编译器需要类的文字,同时也接受字符串的常量?
使用 Spring 的 @RequestMapping 的工作示例:
public class MyController {
public static final String REQUEST_MAPPING = "/index.html";
@RequestMapping(MyController.REQUEST_MAPPING) // ALL OK!
...
}
TestNG 的 @Test 的 WTF 示例:
public class MyControllerTest {
public static final Class TEST_EXCEPTION = RuntimeException.class;
@Test(expectedExceptions = MyControllerTest.TEST_EXCEPTION) // compilation error, WTF:
// The value for annotation attribute Test.expectedExceptions must be a class literal
...
}
当然有效的是 @Test(expectedExceptions = RuntimeException.class)。但为什么?我看到的注释参数的唯一区别是它的类型:String 与 Class。为什么 Java 编译器也接受 String 常量,但只接受类文字?
Java 语言规范不允许您将编译时常量与类型参数一起使用Class
。您只能使用类文字。
The JLS http://java.sun.com/docs/books/jls/third_edition/html/interfaces.html#9.7关于注释的合适参数值有以下说法:
元素类型T与元素值相称V当且仅当以下条件之一为真:
-
T is an array type E[] and either:
-
V is an 元素值数组初始化器和每个元素值初始化器(类似于数组初始值设定项中的变量初始值设定项)V相当于E. Or
-
V is an 元素值相当于T.
- The type of V is assignment compatible (§5.2 http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#184206) with T and, furthermore:
-
If T是原始类型或字符串,V是一个常量表达式(§15.28) http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5313.
-
V不为空。
-
if T是 Class,或者 Class 的调用,V 是类文字(§15.8.2) http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#251530.
- If T是一个枚举类型,并且V是一个枚举常量。
如果元素类型与元素类型不相称,则会出现编译时错误元素值.
不过,我无法解释为什么 JLS 中有此限制。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)