简体   繁体   中英

Use of String.join in Constant Expression

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM