简体   繁体   中英

Groovy: how to concatenate string constants in annotation?

In java I can write @SomeAnnotation("abc"+"cd") . When I do the same in groovy i got compilation error 'expected ... to be an inline constant'. how can i concatenate string constants inside annotations in groovy?

You can't because this expression isn't a compile time constant in Groovy.

You have a few options here

  • Declare a plain Java interface with constants and use it from Groovy

     @SomeAnnotation(Constants.MY_CONST) 
  • If you can change source code of annotation you can try using closure annotation parameters

  • You can also play with compile-time AST transformations here to achieve your goal in a dirty way. (Very probably you don't want to play with AST)

Inability to use expressions like 'aaa' + 'bbb' isn't the only problem, you can see errors like Attribute 'value' should have type 'java.lang.String'; but found type 'java.lang.Object' Attribute 'value' should have type 'java.lang.String'; but found type 'java.lang.Object' even with compile-time expressions. Here is a related issue GROOVY-3278 with possible workarounds.

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