由于属性必须是常量表达式错误,Java 代码无法编译

2022-01-13 00:00:00 string annotations constants spring java

我无法弄清楚为什么以下内容无法编译.IDE 给我的错误是注释属性 RequestParam.defaultValue 的值必须是常量表达式".

I can't figure out why the following won't compile. The error the IDE gives me is "The value for annotation attribute RequestParam.defaultValue must be a constant expression".

我的项目涉及 Spring 和 Maven,具体如下:

My project involves Spring and Maven, and it goes the following:

private static final String MAX_LONG_AS_STRING = Long.toString(Long.MAX_VALUE);

@RequestMapping(method=RequestMethod.GET)
public List<Spittle> spittles(
        @RequestParam(value="max",
                    defaultValue=MAX_LONG_AS_STRING) long max,
        @RequestParam(value="count", defaultValue="20") int count) {
    return spittleRepository.findSpittles(max, count);
}

我认为错误来自 Long 到 String 的转换,但我不知道如何解决它.我将不胜感激任何帮助,我是注释和 Spring 的新手.

I'm thinking the error comes from the conversion of Long to String, but I do not know how to fix it. I will appreciate any help, I am new to annotations and Spring.

推荐答案

Java 规则说,当你有一个注解时,它有一个需要原始类型的参数(例如 int) 或 String,值必须是 常量表达式.[这与 Spring 无关.] 粗略地说,常量表达式是编译器可以在编译时计算出其值的表达式.但是,对于什么构成常量表达式有一些规则.这些规则在 JLS 15.28.只有某些类型的操作可以在常量表达式中使用.诸如 Long.toString() 之类的方法调用不是其中之一.所以使用它会使你的表达式 not 成为一个常量表达式,即使它看起来应该是.(对您来说看起来很像,因为您知道 Long.toString 做了什么.但是,编译器不会保留所有方法的目录来知道哪些是常量"方法,其值可以是在编译时计算出来.)

The Java rules say that when you have an annotation, and it has a parameter that expects a primitive type (such as an int) or a String, the value must be a constant expression. [This has nothing to do with Spring.] Roughly speaking, a constant expression is one whose value the compiler can figure out at compile time. However, there are rules for what constitutes a constant expression. These rules are in JLS 15.28. Only certain types of operations can be used in a constant expression. A method call, such as Long.toString(), isn't one of those. So using that makes your expression not a constant expression, even though it looks like it should be. (It looks like it to you, because you know what Long.toString does. However, the compiler doesn't keep a catalog of all methods to know which ones are "constant" methods whose values can be figured out at compile time.)

但是,链接中的示例显示可以使用 + 运算符,即使其中一个参数不是字符串,因此是 toString() 方法被隐式调用.这表明您可以使事情像这样工作:

However, the example at the link shows that the + operator can be used, even when one of the arguments is not a string and therefore a toString() method is implicitly called. This suggests that you might be able to make things work like this:

private static final String MAX_LONG_AS_STRING = "" + Long.MAX_VALUE;

不过我还没试过.

相关文章