有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java编译器说注释的“值必须是常量”

我有一个Spring1@Controller注释类,带有@RequestMapping注释方法。我想从另一个类中引用@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. 我碰巧正在使用Java8

共 (1) 个答案

  1. # 1 楼答案

    我们需要看看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不是^{} constantRequestMethod.GET是一个enum常数。对于String,这个

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

    是一个常量变量,它是一个常量表达式,因此可以使用

    即使常量在同一个文件中声明,它也不应该工作。请复习