java - 编译器说注释的 "value must be a constant"

标签 java annotations java-8

我有一个带有 @RequestMapping 注释方法的 Spring1 @Controller 注释类。我想从另一个类中引用 @RequestMapping 参数、valuemethod 的值,而不是将它们硬编码到注释中。

例子

代替

@Controller
public class MyController {
    @RequestMapping(value="my/path", method=RequestMethod.GET)
    public String handlePath() {
        // etc...
    }
}

我想要两个文件,

@Controller
public class MyController {
    @RequestMapping(value=Constants.PATH, method=Constants.PATH_METHOD)
    public String handlePath() {
        // etc...
    }
}

public class Constants {
    public static final String PATH = "my/path";
    public static final RequestMethod PATH_METHOD = RequestMethod.GET;
}

不幸的是,此操作失败并出现以下编译时错误:

error: an enum annotation value must be an enum constant
        @RequestMapping(value=Constants.PATH, method=Constants.PATH_METHOD)
                                                              ^

问题

为什么这对 String 有效,但对 enum 无效?


注意事项

  1. 这个问题不是 Spring 特有的,这只是这个问题的一个(希望)可访问的示例。
  2. 我碰巧在使用 Java 8

最佳答案

我们需要看看Java语言规范是怎么说的an acceptable value for an annotation method .

It is a compile-time error if the element type is not commensurate with the element value. An element type T is commensurate with an element value V if and only if one of the following is true:

  • If T is a primitive type or String, then V is a constant expression (§15.28).
  • If T is an enum type (§8.9), then V is an enum constant (§8.9.1).

PATH_METHOD 不是 enum constant . RequestMethod.GET 是一个 enum 常量。对于 String,这

public static final String PATH = "my/path";

是常量变量,是常量表达式,因此可以使用。

即使在同一个文件中声明了常量,它也不应该起作用。请检查。

关于java - 编译器说注释的 "value must be a constant",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26853644/

相关文章:

带有标签的 Javascript/HTML5 图像查看器

java - 有没有办法自动调用对象图上的所有 getter 方法?

java - 如何使用java反射迭代List类型的字段

objective-c - Objective-C : (NSSet *)annotationsInMapRect:(MKMapRect) mapRect method returns null value

java - Comparator.comparing(...) 在采用 String::compareTo 时抛出非静态引用异常

尝试了我能找到的所有方法后,javac 无法被识别(不重复)

java - 当两个接口(interface)有冲突的返回类型时,为什么一个方法成为默认方法?

java - 从 String 反序列化 EnumS 的优雅方式

java - GUI Java应用程序兼容Win7但不兼容Win10

java - 如何读出带冒号的列(:) in its name in hibernate and postgresql