String.intern()

/**
     * 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&trade; 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的多少懂一点,就不解释了。

 

具体的源码以后贴出来,然后其他源码有什么地方使用该方法,大家可以补充。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值