gpt4 book ai didi

java - 如何让java编译器将变量名插入字符串

转载 作者:搜寻专家 更新时间:2023-10-31 19:36:14 25 4
gpt4 key购买 nike

我经常发现自己写的代码是这样的:

throwExceptionWhenEmpty(fileType, "fileType");
throwExceptionWhenEmpty(channel, "channel");
throwExceptionWhenEmpty(url, "url");

throwExceptionWhenEmpty 方法执行如下操作:

private void throwExceptionWhenEmpty(final String var, final String varName) {
if (var == null || var.isEmpty()) {
throw new RuntimeException("Parameter " + varName + " may not be null or empty.");
}
}

我想避免这种将变量名作为字符串传递的明显冗余。 Java 编译器是否可以为我在字符串中插入变量名?

如果我能写出这样的东西我会很高兴:

throwExceptionWhenEmpty(fileType, nameOf(fileType));

最佳答案

这应该可以回答您的问题:SO: How to get name of a variable .

这在 Java 中(很容易)是不可能的。

您可以使用预处理器并将其集成到您的构建过程中。那可能会非常简单和便携。但正如 Stephen C 在评论部分所说,这确实不是 Java 方式,因此不推荐。

关于java - 如何让java编译器将变量名插入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2371559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com