有人可以解释为什么 String 和 Class 注释参数的预期不同吗?为什么编译器需要类的文字,而同时接受字符串的常量?
使用 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 vs Class。为什么 Java 编译器也接受 String 常量但只接受类文字?