In this post, we will see how to resolve Not to hardcode in annotations
Question:
UtilsError



Problem
I try not to hardcode strings in annotations. In the last video there is a partial solution. But, frankly speaking, I failed miserably.
Could you help me? Any solution will suit me (Enums etc.).
Best Answer:
As the error message says, the argument for an annotation must be a constant expression. You can see the definition of a “constant” expression in the JLS:A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly
It then goes on to list the necessary and sufficient conditions for a constant expression. Here are some of the relevant ones:
(a constant expression) is composed using only the following: Literals of primitive type (§3.10.1, §3.10.2, §3.10.3, §3.10.4), string literals (§3.10.5), and text blocks (§3.10.6) The additive operators + and – (§15.18) Simple names (§6.5.6.1) that refer to constant variables (§4.12.4). Qualified names (§6.5.6.2) of the form TypeName . Identifier that refer to constant variables (§4.12.4). […]
And a “constant variable” is (§4.12.4):
a final variable of primitive type or type String that is initialized with a constant expression (§15.29).
Notably, method calls are not constant expressions. One reason is that methods could “complete abruptly”, by throwing an exception for example.
Therefore,
deleteById
is not a constant variable, and so the expression deleteById
is not a constant expression.On the other hand, the expressions
delete + "/{id}"
is a constant expression because delete
and "/{id}"
are constant expressions, and +
applied to constant expressions is also a constant expression.I’d suggest declaring a separate constant called
byId
, if you don’t want to repeatedly write "/{id}"
.delete + byId
directly as the annotation argument.If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com