由于属性必须是常量表达式错误,Java代码将无法编译 [英] Java code won't compile due to attribute must be a constant expression error
问题描述
我无法弄清楚为什么以下不会编译。 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()
)不是其中之一。所以使用它会使你的表达式不是一个常量表达式,即使它看起来应该是这样。 (它看起来像你,因为你知道 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;
我还没试过。
这篇关于由于属性必须是常量表达式错误,Java代码将无法编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!