为什么要避免 Java 中的常量折叠?什么时候?
我在 slf4j 中看到了一些代码,如下所示。我不知道为什么要避免在这里不断折叠。有必要这样做吗?或者只是最佳实践。这样做有什么好处呢?
谢谢。
/**
* Declare the version of the SLF4J API this implementation is compiled against.
* The value of this field is usually modified with each release.
*/
// to avoid constant folding by the compiler, this field must *not* be final
public static String REQUESTED_API_VERSION = "1.6"; // !final**
I saw some codes in slf4j as show below. I don't know why to avoid constant folding in here. Is it necessary to do that? or just best practice. what's the benefit of doing this?
Thanks.
/**
* Declare the version of the SLF4J API this implementation is compiled against.
* The value of this field is usually modified with each release.
*/
// to avoid constant folding by the compiler, this field must *not* be final
public static String REQUESTED_API_VERSION = "1.6"; // !final**
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在发布库的特定情况下,您通常无法控制最终链接到的日志库的最终版本。例如,您使用的是 1.6 版本,而使用您的库的应用程序可能会使用 1.6.1 来修复错误。由于它只是一个点发布,因此 API 应该兼容,但如果您的库检查 SLF4J 版本,它应该显示 1.6.1 而不是 1.6。
如果常量是内联的,即使库在事后升级,您也会看到 1.6(因为它被复制到您的类文件中)。
In the particular case where you are releasing a library, you often don't have control of the final version of the logging library that is eventually linked in at the end. For example you are using version 1.6, and the application that is using your library might use 1.6.1 to get a bugfix. Since it's only a point release the API should be compatible, but if your library inspects the SLF4J version it should show 1.6.1 not 1.6.
If the constant is inlined you will see 1.6 (since it's copied into your class file) even if the library is upgraded after the fact.