/**
* Returns a canonical representation for the string object.
* <p>
* A pool of strings, initially empty, is maintained privately by the
* class {@code String}.
* <p>
* When the intern method is invoked, if the pool already contains a
* string equal to this {@code String} object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this {@code String} object is added to the
* pool and a reference to this {@code String} object is returned.
* <p>
* It follows that for any two strings {@code s} and {@code t},
* {@code s.intern() == t.intern()} is {@code true}
* if and only if {@code s.equals(t)} is {@code true}.
* <p>
* All literal strings and string-valued constant expressions are
* interned. String literals are defined in section 3.10.5 of the
* <cite>The Java™ Language Specification</cite>.
*
* @return a string that has the same contents as this string, but is
* guaranteed to be from a pool of unique strings.
*/
public native String intern();
注释翻译:
该方法调用后,
如果当前String对象与常量池中常量equals比较相等,则该方法返回常量池中常量的引用;
如果当前String对象与常量池中的常量equals比较不相等,则该方法将String对象添加到常量池中,返回常量的引用。
注意:这里只有两个String 对象equals比较相等的情况下,intern()的值才会相等
为什么会有这个方法?用来做什么用的?
这里我在看dubbo的源码发现使用到。在消费端与服务端通信时,需要序列化请求参数。
这里每次服务调用,都需要将具体摸个服务(如:com.demo.helloService.sayHello())序列化。这里假如com.demo.helloService这个接口有很多服务(如:sayHi()),这里服务会增加,但是接口名com.demo.helloService时不变的,这时候,dubbo在处理接口名的时候,将com.demo.helloService 这个接口名通过String.intern方法,放入常量池中。
为什么放到常量池中,这个学Java的多少懂一点,就不解释了。
具体的源码以后贴出来,然后其他源码有什么地方使用该方法,大家可以补充。