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.
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.