在 Java 中使用常量变量进行字符串插值?

问题描述 投票:0回答:2

我将 String 变量保存在 Constant 类中,如下所示:

public final class Constants {

    private Constants() {}

    public static final String NOT_FOUND = "Requested record is not found : %s";

    // ...
}

然后使用

String.Format()
方法插入参数,例如:

.orElseThrow(() -> 
new NoSuchElementFoundException(String.format(NOT_FOUND , entity.getId()));

我尝试使用大括号,但如果不使用

String.Format()
方法就无法进行插值。这可能吗?我有没有弄错?

public static final String NOT_FOUND = "Requested record is not found : {0}";

更新: 我已经有一个自定义异常处理程序,如下所示:

public class NoSuchElementFoundException extends RuntimeException {

    public NoSuchElementFoundException() {
        super();
    }

    public NoSuchElementFoundException(String message) {
        super(message);
    }

    public NoSuchElementFoundException(String message, Throwable cause) {
        super(message, cause);
    }
}
java spring string spring-boot interpolation
2个回答
1
投票

String.format() 的 % 语法是正确的。花括号 {} 无效。

我想您可能会想到 MessageFormat,它使用 {},例如

MessageFormat.format("请求记录未找到:{0}", entity.getId()))

看看这个问题.

这是最好的方法吗?我的偏好是创建一个扩展 NoSuchElementFoundException 的自定义异常,仅将 id 作为参数并格式化消息(与内部 String.format() 相同的方式。我认为它更干净。


0
投票

在您的原始示例中,某些日志记录框架对消息字符串进行了有限的插值。但它依赖于日志记录框架。

在当前示例中,(通常)未指定标准 Java SE 异常构造函数来插入参数。所以他们没有。

与(比方说)Python 不同,Java 语言目前不提供任何语法等来支持字符串插值。 Java 21 中有一个预览版;见https://bugs.openjdk.org/browse/JDK-8273943

© www.soinside.com 2019 - 2024. All rights reserved.