我想在注释元素中提供的String
中使用特定于平台的换行符。
我应该在下面使用什么而不是???
?
@Scenario(title = "This text should match multiline text from file stored on disk " + ???
+ "saved with platform specific newline character")
当我用???
替换System.lineSeparator()
时,我收到编译错误Attribute value must be constant
。有什么想法吗?
答案 0 :(得分:2)
这是不可能的。注释参数值必须是编译时常量。你得到的错误也是如此。
根据定义,依赖于平台的值不是编译时常量,因为它应该根据您运行它的平台而有所不同。所以它不能是注释参数值的一部分。
您可以在输出参数值的地方进行翻译,将每个\n
替换为System.lineSeparator()
。
答案 1 :(得分:2)
无法使用非常量值作为注释的属性。您提交给注释的字符串必须是compile-time constant as specified in JLS §15.28。
在类文件中,注释属性直接存储为元数据和注释的声明。因此,根据概念,无法在运行时解析属性,因为解析依赖于运行时的属性是必需的。
作为替代方案,您应该更好地对注释的属性进行后处理,例如:只需用运行时的System.getProperty("line.separator")
值替换字符串的换行符。
答案 2 :(得分:1)
你可以做的是引入一个常量表达式:
private static final String LINE_SEPARATOR = "\n";
并在注释中使用它:
@Scenario(title = "This text should match multiline text from file stored on disk "
+ LINE_SEPARATOR
+ "saved with platform specific newline character")
但是LINE_SEPARATOR
本身必须是常量,不能使用System.lineSeparator()
进行初始化。至少它可以让您更容易一次更改所有注释中的行分隔符...
或者,您可以更改注释以接受一系列行:
public @interface Scenario {
String[] titleLines();
}
并附注:
@Scenario(titleLines = {"This text should match multiline text from file stored on disk ",
"saved with platform specific newline character" })
然后,您可以根据需要在使用注释的代码中插入行分隔符。
答案 3 :(得分:0)
Java只知道格式字符串:String.format("%n")
。因此,如果注释以某种方式传递给格式化程序,那么可能会尝试。机会很小。
否则Windows的“\ r \ n”可能无处不在。