注释中平台特定的换行符
Platform specific newline character in annotation
我想在注释元素中提供的 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
。有什么想法吗?
这不可能。注释参数值必须是编译时常量。你得到的错误说的是一样的。
根据定义,依赖于平台的值不是编译时常量,因为它应该根据您 运行 它所处的平台而有所不同。所以它不能是注释参数值的一部分。
您可以在输出参数值的地方进行翻译,将每个 \n
替换为 System.lineSeparator()
。
不能使用非常量值作为注释的属性。您传递给注释的字符串必须是 compile-time constant as specified in JLS §15.28。
在 class 文件中,注释属性作为元数据与注释声明直接存储在一起。因此,从概念上讲,属性不能在运行时解析,因为解析依赖于运行时的属性是必需的 属性.
作为替代方案,您应该 post 处理注释的 属性,例如通过简单地用运行时的 System.getProperty("line.separator")
值替换字符串的换行符。
你可以做的是引入一个常量表达式:
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" })
然后你可以在使用注解的代码中根据需要插入一个行分隔符。
Java 只知道格式字符串来做到这一点:String.format("%n")
。因此,如果注释以某种方式传递给格式化程序,则可能会尝试这样做。机会渺茫。
否则 "\r\n" for Windows 可能无处不在。
我想在注释元素中提供的 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
。有什么想法吗?
这不可能。注释参数值必须是编译时常量。你得到的错误说的是一样的。
根据定义,依赖于平台的值不是编译时常量,因为它应该根据您 运行 它所处的平台而有所不同。所以它不能是注释参数值的一部分。
您可以在输出参数值的地方进行翻译,将每个 \n
替换为 System.lineSeparator()
。
不能使用非常量值作为注释的属性。您传递给注释的字符串必须是 compile-time constant as specified in JLS §15.28。
在 class 文件中,注释属性作为元数据与注释声明直接存储在一起。因此,从概念上讲,属性不能在运行时解析,因为解析依赖于运行时的属性是必需的 属性.
作为替代方案,您应该 post 处理注释的 属性,例如通过简单地用运行时的 System.getProperty("line.separator")
值替换字符串的换行符。
你可以做的是引入一个常量表达式:
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" })
然后你可以在使用注解的代码中根据需要插入一个行分隔符。
Java 只知道格式字符串来做到这一点:String.format("%n")
。因此,如果注释以某种方式传递给格式化程序,则可能会尝试这样做。机会渺茫。
否则 "\r\n" for Windows 可能无处不在。