Java - tell if a String is interned?

前端 未结 4 1985
难免孤独
难免孤独 2020-12-10 12:43

So the question here is pretty simple: is there a way to tell if a String in Java is interned? My guess is no, but I\'m wondering if anyone knows better.

4条回答
  •  执笔经年
    2020-12-10 12:58

    The only way you can find out if a String is interned is to call intern() and check if it returns itself:

    boolean hasBeenInternedBefore = myString.intern() == myString;
    

    This obviously has the drawback of interning the String when it wasn't interned before.

    Going partially off-topic, there's a way to do "custom" interning with an explicit pool using the Interner interface of Guava (using the implementations exposed by the Interners class). This has the advantage of being able to let the Interner itself (and thuse the pool) being garbage collected when it's no longer referenced.

提交回复
热议问题