在Java中有更优雅的方式吗?
String value1 = "Testing";
String test = "text goes here " + value1 + " more text";
Run Code Online (Sandbox Code Playgroud)
是否可以将变量直接放在字符串中并评估其值?
dfa*_*dfa 54
String test = String.format("test goes here %s more text", "Testing");
Run Code Online (Sandbox Code Playgroud)
是你用Java写的最接近的东西
too*_*kit 27
更优雅的方式可能是:
String value = "Testing";
String template = "text goes here %s more text";
String result = String.format(template, value);
Run Code Online (Sandbox Code Playgroud)
或者使用MessageFormat:
String template = "text goes here {0} more text";
String result = MessageFormat.format(template, value);
Run Code Online (Sandbox Code Playgroud)
请注意,如果您正在执行此操作以进行日志记录,则可以避免在日志行低于阈值时执行此操作的成本.例如使用SLFJ:
以下两行将产生完全相同的输出.但是,在禁用日志记录语句的情况下,第二种形式的性能将比第一种形式的性能至少提高30倍.
logger.debug("The new entry is "+entry+".");
logger.debug("The new entry is {}.", entry);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45507 次 |
| 最近记录: |