How to check String Pool Contents?

本秂侑毒 提交于 2019-12-03 01:16:22

You are not able to access the string pool from Java code, at least not in the HotSpot implementation of Java VM.

String pool in Java is implemented using string interning. According to JLS §3.10.5:

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.

And according to JLS §15.28:

Compile-time constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern.

String.intern is a native method, as we can see in its declaration in OpenJDK:

public native String intern();

The native code for this method calls JVM_InternString function.

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

That is, string interning is implemented using native code, and there's no Java API to access the string pool directly. You may, however, be able to write a native method yourself for this purpose.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!