您无法从Java代码访问字符串池,至少不能在Java VM的HotSpot实现中。
a string literal always refers to the same instance of class String. This is because string literals – or, more generally, strings that are the values of constant expressions (§15.28) – are “interned” so as to share unique instances, using the method String.intern.
Compile-time constant expressions of type String are always “interned” so as to share unique instances, using the method String.intern.
String.intern是一种本机方法,我们可以在its declaration in OpenJDK看到:
public native String intern();
JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
JVMWrapper("JVM_InternString");
JvmtiVMObjectAllocEventCollector oam;
if (str == NULL) return NULL;
oop string = JNIHandles::resolve_non_null(str);
oop result = StringTable::intern(string, CHECK_NULL);
return (jstring) JNIHandles::make_local(env, result);
JVM_END
也就是说,使用本机代码实现字符串实习,并且没有Java API直接访问字符串池。但是,您可以为此而自己编写本地方法。