The compiler says that the annotation value should be constant,

I have an annotated Spring 1 class @Controller

with annotated methods @RequestMapping

. I want to reference the parameter values @RequestMapping

, value

and method

, from another class, not hard-code them into an annotation.

Example

Instead

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

      

I want two files,

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

      

and

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

      

Unfortunately this fails on the following compile-time error:

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

      

Question

Why does this work for the case String

, but not for enum

s?


Notes

  • This question is not Spring specific, it is just (hopefully) an accessible example of this problem.
  • I am using Java 8
+3


source to share


1 answer


We need to see what the Java Language spec says an acceptable value for an annotation method .

It is a compile-time error if the element type is not commensurate with the element size. The element type is T

commensurate with the element value V

if and only if one of the following conditions is met:

  • If T

    is a primitive type or String

    , then it V

    is a constant expression (ยง15.28).
  • If T

    is a type enum

    (ยง8.9), then V is a constant enum

    (ยง8.9.1).

PATH_METHOD

is not constant enum

. RequestMethod.GET

is a constant enum

. For String

this



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

      

- constant variable, which is a constant expression and therefore can be used.

It shouldn't work even if the constant was declared in the same file. Please review.

+4


source







All Articles