何时在String文字上使用intern() [英] When to use intern() on String literals

查看:105
本文介绍了何时在String文字上使用intern()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多这样的遗留代码:

I see a lot of legacy code like this:

class A {
    public static final String CONSTANT = "value".intern();
    ...
}

我认为没有任何理由intern(),就像在Javadoc中一样,可以读取:所有文字字符串和字符串值常量表达式都是实例化的。是否有一些这样的意图,可能是在语言的过去修订中?

I don't see any reason for the intern(), as in the Javadoc one can read: "All literal strings and string-valued constant expressions are interned." Is there some intent of this, maybe in past revisions of the language?

推荐答案

这是一种确保<$ c的技术$ c> CONSTANT 实际上不是常量。

This is a technique to ensure that CONSTANT is not actually a constant.

当Java编译器看到对最终静态原语或String的引用时,它会插入该常量的实际值到使用它的类中。如果然后更改定义类中的常量值但不重新编译using类,它将继续使用旧值。

When the Java compiler sees a reference to a final static primitive or String, it inserts the actual value of that constant into the class that uses it. If you then change the constant value in the defining class but don't recompile the using class, it will continue to use the old value.

通过调用intern()on 常量字符串,编译器不再将其视为静态常量,因此using类实际上将在每次使用时访问定义类的成员。

By calling intern() on the "constant" string, it is no longer considered a static constant by the compiler, so the using class will actually access the defining class' member on each use.

JLS引用:

对编译时常量的更改意味着(大约是页面的一半): http://docs.oracle.com/javase/specs/jls/ se6 / html / binaryComp.html#45139

implication of changes to a compile-time constant (about halfway down the page): http://docs.oracle.com/javase/specs/jls/se6/html/binaryComp.html#45139

这篇关于何时在String文字上使用intern()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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