3

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).

Samuel Barr
  • 434
  • 4
  • 12

1 Answers1

4

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Darn. It'd be convenient if the compiler were able to special case certain expressions, but there may very well be a reason that's not possible. – Samuel Barr Jun 18 '19 at 21:35
  • 1
    @SamuelBarr there’s ongoing research in that direction, see https://openjdk.java.net/jeps/303#Constant-propagation and https://cr.openjdk.java.net/~briangoetz/amber/constables.html#constant-tracking-propagation-and-folding – Holger Jul 11 '19 at 14:34