简体   繁体   English

Groovy:如何在注释中连接字符串常量?

[英]Groovy: how to concatenate string constants in annotation?

In java I can write @SomeAnnotation("abc"+"cd") . 在java中,我可以编写@SomeAnnotation("abc"+"cd") When I do the same in groovy i got compilation error 'expected ... to be an inline constant'. 当我在groovy中做同样的事情时,我得到了编译错误'期望...是一个内联常量'。 how can i concatenate string constants inside annotations in groovy? 如何在groovy中的注释中连接字符串常量?

You can't because this expression isn't a compile time constant in Groovy. 你不能,因为这个表达式不是Groovy中的编译时常量。

You have a few options here 你有几个选择

  • Declare a plain Java interface with constants and use it from Groovy 使用常量声明一个普通的Java接口,并在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. 您还可以在此处使用编译时AST转换来以肮脏的方式实现您的目标。 (Very probably you don't want to play with AST) (很可能你不想玩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' 无法使用像'aaa' + 'bbb'这样'aaa' + 'bbb'表达式不是唯一的问题,你可以看到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' Attribute 'value' should have type 'java.lang.String'; but found type 'java.lang.Object' even with compile-time expressions. 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' Here is a related issue GROOVY-3278 with possible workarounds. 这是一个相关问题GROOVY-3278 ,可能有解决方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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