I have a very long String
constant which is used for an annotation, and this string is essentially a comma separated list. What I would like to be able to do is the following:
String str = String.join(", ", "abc", "def", "ghi", "jkl");
@Annotation(str)
public void foo();
But I get the error element value must be a constant expression
. I understand that the expression does not fit into Java's definition of a constant expression, however, is there any way to assert to the compiler that str
is constant? The code is much easier to read and maintain if I can write it in the above fashion (the actual list is much longer in my actual code).
No.
A constant expression has a precise definition in the language spec, and anything involving a method invocation is not a constant expression.
The only way you could make this a constant expression would be by generating code containing the result of that method, compiling it, and using the constant-valued expression from that.