注释属性必须是类文本吗?为什么?常量也应该没问题
有人可以解释为什么字符串和类注释参数的期望不同吗?为什么编译器需要类的文字,同时也接受字符串的常量?
Spring@RequestMapping的工作示例:
public class MyController {
public static final String REQUEST_MAPPING = "/index.html";
@RequestMapping(MyController.REQUEST_MAPPING) // ALL OK!
...
}
WTF示例与TestNG的@Test:
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)。但是为什么?我看到的注释参数的唯一区别是它的类型:字符串与类。为什么Java编译器也接受String常量,但只接受类文本?