是否所有编译时常量都内联? [英] Are all compile-time constants inlined?

查看:245
本文介绍了是否所有编译时常量都内联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样一个类:

class ApplicationDefs{
public static final String configOption1 = "some option";
public static final String configOption2 = "some other option";
public static final String configOption3 = "yet another option";
}

我的应用程序中的许多其他类都使用这些选项。现在,我想单独更改其中一个选项并仅部署已编译的类。
但是如果这些字段在消费者类中是内联的,这就不可能了吗?

Many of the other classes in my application are using these options. Now, I want to change one of the options alone and deploy just the compiled class. But if these fields are in-lined in the consumer classes this becomes impossible right?

是否有任何选项可以禁用编译时常量的内联?

Is there any option to disable the in-lining of compile time constants?

推荐答案

您可以使用String.intern()来获得所需的效果,但应该注释您的代码,因为没有多少人知道这个。即。

You can use String.intern() to get the desired effect, but should comment your code, because not many people know about this. i.e.

public static final String configOption1 = "some option".intern();

这将阻止内联编译时间。因为它指的是编译器将在烫发中放置的完全相同的字符串,所以你不会创建任何额外的字符串。

This will prevent the compile time inline. Since it is referring to the exact same string that the compiler will place in the perm, you aren't creating anything extra.

作为替代方案,你可以随时做

As an alternative you could always do

public static final String configOption1 = "some option".toString();

但是这不会使用编译的实习字符串,它会在旧的字符串上创建一个新字符串根。这不是一个大问题,也可能更容易阅读。无论哪种方式,因为这有点奇怪,你应该评论代码,以通知那些维护它你正在做什么。

however this will not use the compiled intern'd string, it will create a new one on the old gen. Not a huge big deal, and might be easier to read. Either way, since this is a bit odd you should comment the code to inform those maintaining it what you are doing.

编辑:
找到另一个SO链接,提供对JLS的引用,以获取有关此内容的更多信息。
何时在字符串文字上使用intern()

这篇关于是否所有编译时常量都内联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆